我正在使用 ExpressJS 编写我的应用程序和 jsonfile ( https://www.npmjs.com/package/jsonfile ) 来处理 json 文件。我有以下 json 文件:
{
"news": [
{
"id": "1",
"title": "News 1 heading",
"description": "Lorem ipsum dolor sit amet upidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"dateposted": "00188292929"
},
{
"id": "2",
"title": "News 2 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
}
]
}
现在,我想在“news” Node 下添加另一组新闻,这样我的最终 json 如下所示:
{
"news": [
{
"id": "1",
"title": "News 1 heading",
"description": "Lorem ipsum dolor sit amet upidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"dateposted": "00188292929"
},
{
"id": "2",
"title": "News 2 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
},
{
"id": "3",
"title": "News 3 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
}
]
}
jsonfile 有一个附加标志,但它附加在文件末尾而不是在给定 Node 下。如何在现有 Node 下追加数据?我需要对 json 进行字符串化,添加数据并进行 JSONfy 吗?或者有更直接的方法吗?
谢谢。
最佳答案
您可以使用 Json PUSH 将 json 对象附加到当前 Node 。代码如下所示:
var json={
"news": [
{
"id": "1",
"title": "News 1 heading",
"description": "Lorem ipsum dolor sit amet upidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"dateposted": "00188292929"
},
{
"id": "2",
"title": "News 2 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
},
{
"id": "3",
"title": "News 3 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
}
]
};
json.news.push({
"id": "3",
"title": "News 3 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
});
console.log(json);
关于json - 如何通过node js向现有的json文件添加子 Node ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49128908/