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



我有以下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);
});

一旦解析了数据,现在您的对象就在内存中,您可以随心所欲地使用它。你可以通过以下方式提取你所说的行

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

最新更新