javascript - 在 Node.js 中顺序解析 JSON

标签 javascript node.js

我正在尝试在 Node.js 中解析一些 JSON。 JSON 来自 .json 文件。我认为由于 Node 的异步特性,我错过了一些东西。但是,我不确定如何超越它。目前,我正在尝试以下代码:

var results = null;

// Read the .json file
var file = __dirname + '/config.json';
fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    return;
  }

  results = JSON.parse(data);
  console.log(results.count);
});

// iterate through keys in results and print them out one at a time.

每当我运行此代码时,最后一行 console.log 都会打印“未定义”。因此,我什至还没有尝试过迭代这些键。但是,我知道我正在正确加载 .json 文件,因为当我执行以下操作时,我看到了预期的结果:

results = JSON.parse(data, function(k, v) {
  console.log(k + ' : ' + v);
});

这就是为什么我怀疑它与 Node 的异步性质有关。但是,我不确定如何解决这个问题。

感谢您的帮助。

最佳答案

您的 JSON 不是具有 count 属性的对象。

<小时/>
results = JSON.parse(data, function(k, v) {
  console.log(k + ' : ' + v);
});

打印内容,因为回调是“reviver”,并接收每个键和值。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

如果你这样做

results = JSON.parse(data);
for(var k in results) {
    console.log(k + ' : ' + results[k]);
}

你会看到同样的事情。

关于javascript - 在 Node.js 中顺序解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23400993/

相关文章:

html - 带有 CSS 的外部 HTML 文件作为 nodemailer 中的电子邮件内容

javascript - Nightmarejs 同一测试中的多个页面

javascript - ul 中的交换列表和事件元素位置保持不变

javascript - jQuery-Toggler 内指向 "hidden"内容(某个 #id)的超链接

javascript - 图像失去 CamanJS 对操作 Canvas 的影响

node.js - 将不需要的功能(fdescribe、describe.only)检测为 Gulp 任务

node.js - 已解决 : Getting onTurnError when sending adaptive card to MS Teams using Bot Framework SDK 4

javascript - Amcharts 类别轴也显示空数据的日期

javascript - 是否可以在字符串模板中插入 Javascript 正则表达式匹配?

javascript - 平均堆栈 : Bcrypt is not hashing my password