简体   繁体   English

在Node.js中顺序解析JSON

[英]Parsing JSON sequentially in Node.js

I'm trying to parse some JSON in Node.js. 我正在尝试在Node.js中解析一些JSON。 The JSON comes from a .json file. JSON来自.json文件。 I think I'm missing something due to Node's asynchronous nature. 我认为由于Node的异步特性,我缺少了一些东西。 However, I'm not sure how to get beyond it. 但是,我不确定如何超越它。 Currently, I'm trying the following code: 目前,我正在尝试以下代码:

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.

Whenever I run this code, the last console.log line prints 'undefined'. 每当我运行此代码时,最后一个console.log行都会显示“ undefined”。 For that reason, I haven't even tried iterating through the keys yet. 因此,我什至没有尝试过遍历这些键。 However, I know I'm loading the .json file properly because when I do the following, I see the expected results: 但是,我知道我正在正确加载.json文件,因为当我执行以下操作时,我看到了预期的结果:

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

That's why I suspect it has something to do with the async nature of node. 这就是为什么我怀疑它与节点的异步特性有关。 However, I'm not sure how to get around this. 但是,我不确定该如何解决。

Thank you for your help. 谢谢您的帮助。

Your JSON is not an object with a count property. 您的JSON不是具有count属性的对象。


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

prints stuff because the callback is a "reviver", and receives each key and value. 打印内容,因为回调是“ reviver”,并接收每个键和值。

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

If you do 如果你这样做

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

you will see the same thing. 您将看到同一件事。

Just to point out the obvious what you are probably trying to do with results.count should instead be: 只是为了指出显而易见的结果,您可能想对results.count进行处理,而应该是:

Object.keys(results).length;

But that won't give you the length including child properties only the direct keys. 但这不会给您包括子属性(仅包含直接键)的长度。

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

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