简体   繁体   English

节点 fs.readfile 读取 json object 属性

[英]node fs.readfile reading json object property

I have the following json file.我有以下 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."
  }
}

By using fs.readFile, I am trying to display only the properties like the follows.通过使用 fs.readFile,我试图只显示如下属性。 1:The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared. 1:事件循环是 JavaScript 运行时在堆栈被清除后将异步回调推送到堆栈上的方式。 2:Prototypal inheritance is how JavaScript objects delegate behavior. 2:原型 inheritance 是 JavaScript 对象委托行为的方式。

But my code shows the whole JSON file.但我的代码显示了整个 JSON 文件。 My code is as follows:我的代码如下:

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);
});

Well once you parsed the data now you have your object in memory and you can operate with it as you wish.好吧,一旦您解析了数据,现在您的 object 就在 memory 中,您可以随意使用它。 You can extract the lines you tell about in the following way您可以通过以下方式提取您讲述的行

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

Note, here we are using numbers in string because you saved your messages as an object, where keys are strings.请注意,这里我们使用字符串中的数字,因为您将消息保存为 object,其中键是字符串。 If you want to access that as an array you need to save that in the following way.如果您想以数组的形式访问它,您需要按以下方式保存它。

{
  "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."
  ]
}

Then you could do the following thing.然后你可以做以下事情。

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

And because it is an array now you could iterate over it.而且因为它现在是一个数组,所以您可以对其进行迭代。

UPD: Based on comment. UPD:根据评论。

If you need to loop over keys and values then it can help.如果您需要遍历键和值,那么它会有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM