节点 fs.readfile 读取 json 对象 属性

node fs.readfile reading json object property

我有以下 json 文件。

{
  "nextId": 5,
  "notes": {
    "1": "The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared.",
    "2": "Prototypal inheritance is how JavaScript objects delegate behavior.",
    "3": "In JavaScript, the value of `this` is determined when a function is called; not when it is defined.",
    "4": "A closure is formed when a function retains access to variables in its lexical scope."
  }
}

通过使用 fs.readFile,我试图只显示如下所示的属性。 1:The 事件循环是 JavaScript 运行时在堆栈被清除后将异步回调推送到堆栈的方式。 2:Prototypal 继承是 JavaScript 对象委托行为的方式。

但我的代码显示了整个 JSON 文件。我的代码如下:

const fs = require('fs');
const fileName = 'data.json';

fs.readFile(fileName, 'utf8', (err, data) => {
    if (err) throw err;

    const databases= JSON.parse(data);

    //databases.forEach(db=>{
    console.log(databases);
    //});
    //console.log(databases);
});

一旦你解析了数据,你的对象就在内存中了,你可以随意操作它。 您可以通过以下方式提取您讲述的台词

databases.notes["1"];
databases.notes["2"];

注意,这里我们使用字符串中的数字,因为您将消息保存为对象,其中键是字符串。如果您想将其作为数组访问,您需要按以下方式保存它。

{
  "nextId": 5,
  "notes": [
    "The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared.",
    "Prototypal inheritance is how JavaScript objects delegate behavior.",
    "In JavaScript, the value of `this` is determined when a function is called; not when it is defined.",
    "A closure is formed when a function retains access to variables in its lexical scope."
  ]
}

然后你可以做下面的事情。

databases.notes[0];
databases.notes[1];

因为它现在是一个数组,所以您可以对其进行迭代。

UPD:基于评论。

如果您需要遍历键和值,它会有所帮助。

for (const [key, value] of Object.entries(databases.notes)) {
    console.log(key);
    console.log(value);
}