json - 如何通过node js向现有的json文件添加子 Node ?

标签 json node.js express

我正在使用 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/

相关文章:

node.js - dust.js 通过函数格式化文本

javascript - 是否可以将相对 URL 提供给 Phantom.js 页面生成器来获取 PDF 渲染?

node.js - 无法卸载 NVM 包

node.js - 在 Jade 中添加页脚或其他部分

c++ - 格式化包含引号的字符串

c# - 使用 Json.NET 反序列化带有数组数组的 json 字符串

node.js - Mongoose 填充 - 数组

javascript - NodeJS : 'toString()' failed when require a large JSON file

javascript - GET 请求适用于 Postman,但为什么不适用于 ReactJS fetch?

c# - 在 C# restful web 服务中删除 xml 命名空间返回字符串