我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?


当前回答

您可以使用JSON.parse()(这是一个内置函数,可能会强制您使用try-catch语句包装它)。

或者使用一些JSON解析npm库,比如JSON -parse- Or

其他回答

只是为了让这个问题尽可能复杂,并引入尽可能多的包……

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

这让你做:

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

或者如果你使用async/await:

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

与仅使用readFileSync相比的优点是,在从磁盘读取文件时,Node服务器可以处理其他请求。

JSON.parse("your string");

这是所有。

解析JSON流?使用JSONStream。

var request = require('request')
  , JSONStream = require('JSONStream')

request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
    .pipe(JSONStream.parse('rows.*'))
    .pipe(es.mapSync(function (data) {
      return data
    }))

https://github.com/dominictarr/JSONStream

正如这里提到的其他答案,你可能想要一个本地json文件,你知道是安全的,就像一个配置文件:

var objectFromRequire = require('path/to/my/config.json'); 

或者使用全局JSON对象将字符串值解析为对象:

var stringContainingJson = '\"json that is obtained from somewhere\"';
var objectFromParse = JSON.parse(stringContainingJson);

请注意,当您需要一个文件时,该文件的内容会被评估,如果它不是json文件而是js文件,则会引入安全风险。

在这里,我发布了一个演示,你可以看到这两种方法,并在线使用它们(解析示例在app.js文件中-然后点击运行按钮,在终端中看到结果): http://staging1.codefresh.io/labs/api/env/json-parse-example

您可以修改代码并查看影响…

如果你需要用Node.js以一种安全的方式解析JSON(也就是说:用户可以输入数据,或者一个公共API),我建议使用secure- JSON -parse。

其用法类似于默认的JSON。解析,但它会保护你的代码:

原型中毒 和构造函数滥用:

const badJson = '{ "a": 5, "b": 6, "__proto__": { "x": 7 }, "constructor": {"prototype": {"bar": "baz"} } }'

const infected = JSON.parse(badJson)
console.log(infected.x) // print undefined

const x = Object.assign({}, infected)
console.log(x.x) // print 7

const sjson = require('secure-json-parse')
console.log(sjson.parse(badJson)) // it will throw by default, you can ignore malicious data also