简体   繁体   中英

Parsing JSON sequentially in Node.js

I'm trying to parse some JSON in Node.js. The JSON comes from a .json file. I think I'm missing something due to Node's asynchronous nature. 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'. 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:

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.


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.

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:

Object.keys(results).length;

But that won't give you the length including child properties only the direct keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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