如何通过节点 js 将子节点添加到现有 json 文件中



我正在使用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"节点下添加另一组新闻,以便我的最终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);
   

Jsonfile 的追加选项是指在追加模式下打开文件,在此模式下您只能添加到文件的末尾。

您需要使用普通的 writeFile 选项重写整个文件。有效地覆盖原始文件。

您可以在第 91 行的 jsonfile 代码(它是一个简短的单文件节点模块(中看到,它只是将 append 标志传递给 fs.writeFile。老实说,我不完全确定您何时会使用它,但我假设如果您想输出一堆文档,然后在每个文档的底部附加一些 json。

最新更新