我正在尝试适应nodejs的基础知识,我正在尝试将数据推送到现有的JSON文件,但我得到了无法读取未定义的属性“推送”。
代码:
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"}
}
]
}
最佳答案
JSON 文件中缺少
table
加载文件并调用 obj = JSON.parse(data);
obj.table
不再存在,因为它将覆盖您上面定义的内容。
关于arrays - Node.js 写入现有地理位置 JSON 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58231859/