【问题标题】:node fs.readfile reading json object property节点 fs.readfile 读取 json 对象属性
【发布时间】:2021-05-08 06:16:36
【问题描述】:

我有以下 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:事件循环是 JavaScript 运行时在堆栈被清除后将异步回调推送到堆栈上的方式。 2:原型继承是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);
});

【问题讨论】:

    标签: javascript node.js json object readfile


    【解决方案1】:

    好吧,一旦您解析了数据,现在您的对象就在内存中,您可以根据需要对其进行操作。 您可以通过以下方式提取您讲述的行

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

    【讨论】:

    • 顺便说一句,您可以使用 require 从 JSON 文件中获取对象。将您的代码替换为以下javascript const data = require('./data.json') console.log(data.notes)
    • 这行得通,但我也想显示键,以及整个键和属性。我想我需要遍历“notes”对象。但我不知道该怎么做。
    • @yusuf 我已根据您的评论更新了答案。如果有帮助,请将答案标记为正确
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多