Node.js写入现有地理位置JSON错误
我试图习惯于nodejs的基础,我试图将数据推送到现有的JSON文件,但是我得到了无法读取的属性'push',未定义。
产品编号:
var obj = {
table: []
};
var app = express();
app.get('/parseData', function (req, res) {
var fs = require('fs');
fs.readFile('./json/locationData.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"prop0": "value0"}}
); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('./json/locationData.json', json, 'utf8', callback); // write it back
res.header("Content-Type",'application/json');
res.send(json);
}});
});
app.listen(3000);
JSON文件:
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"prop0": "value0"}
},
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [103.0, 0.5]},
"properties": {"prop0": "value0"}
}
]
}
回答如下:[table
从JSON文件中丢失
Node.js写入现有地理位置JSON错误
我试图习惯于nodejs的基础,我试图将数据推送到现有的JSON文件,但是我得到了无法读取的属性'push',未定义。
产品编号:
var obj = {
table: []
};
var app = express();
app.get('/parseData', function (req, res) {
var fs = require('fs');
fs.readFile('./json/locationData.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"prop0": "value0"}}
); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('./json/locationData.json', json, 'utf8', callback); // write it back
res.header("Content-Type",'application/json');
res.send(json);
}});
});
app.listen(3000);
JSON文件:
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"prop0": "value0"}
},
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [103.0, 0.5]},
"properties": {"prop0": "value0"}
}
]
}
回答如下:[table
从JSON文件中丢失