How to parse JSON using Node.js?

2018-12-31 10:30发布

How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?

30条回答
残风、尘缘若梦
2楼-- · 2018-12-31 10:54

Just want to complete the answer (as I struggled with it for a while), want to show how to access the json information, this example shows accessing Json Array:

var request = require('request');
request('https://server/run?oper=get_groups_joined_by_user_id&user_id=5111298845048832', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var jsonArr = JSON.parse(body);
    console.log(jsonArr);
    console.log("group id:" + jsonArr[0].id);
  }
})

查看更多
时光乱了年华
3楼-- · 2018-12-31 10:55

My solution:

var fs = require('fs');
var file = __dirname + '/config.json';

fs.readFile(file, 'utf8', function (err, data) {
    if (err) {
        console.log('Error: ' + err);
        return;
    }

    data = JSON.parse(data);

    console.dir(data);
});
查看更多
刘海飞了
4楼-- · 2018-12-31 10:57

Another example of JSON.parse :

var fs = require('fs');
var file = __dirname + '/config.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }

  data = JSON.parse(data);

  console.dir(data);
});
查看更多
高级女魔头
5楼-- · 2018-12-31 10:58

If you want to add some comments in your JSON and allow trailing commas you might want use below implemention:

var fs = require('fs');

var data = parseJsData('./message.json');

console.log('[INFO] data:', data);

function parseJsData(filename) {
    var json = fs.readFileSync(filename, 'utf8')
        .replace(/\s*\/\/.+/g, '')
        .replace(/,(\s*\})/g, '}')
    ;
    return JSON.parse(json);
}

Note that it might not work well if you have something like "abc": "foo // bar" in your JSON. So YMMV.

查看更多
刘海飞了
6楼-- · 2018-12-31 10:59

JSON.parse will not ensure safety of json string you are parsing. You should look at a library like json-safe-parse or a similar library.

From json-safe-parse npm page:

JSON.parse is great, but it has one serious flaw in the context of JavaScript: it allows you to override inherited properties. This can become an issue if you are parsing JSON from an untrusted source (eg: a user), and calling functions on it you would expect to exist.

查看更多
爱死公子算了
7楼-- · 2018-12-31 11:01

Just to make this as complicated as possible, and bring in as many packages as possible...

const fs = require('fs');
const bluebird = require('bluebird');
const _ = require('lodash');
const readTextFile = _.partial(bluebird.promisify(fs.readFile), _, {encoding:'utf8',flag:'r'});
const readJsonFile = filename => readTextFile(filename).then(JSON.parse);

This lets you do:

var dataPromise = readJsonFile("foo.json");
dataPromise.then(console.log);

Or if you're using async/await:

let data = await readJsonFile("foo.json");

The advantage over just using readFileSync is that your Node server can process other requests while the file is being read off disk.

查看更多
登录 后发表回答