我正在使用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"
}
]
}
现在,我想在“新闻”节点下添加另一组新闻,这样我的最终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中有一个附加标志,但它附加在文件末尾而不是在给定节点下。如何在现有节点下附加数据?我需要对json进行字符串化,添加数据并对其进行JSONfy吗?还是有更直接的方法?
谢谢。
最佳答案
您可以使用Json PUSH将json对象附加到当前节点。代码如下所示:
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将子 Node 添加到现有json文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49128908/