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


当前回答

解析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.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。解析将不能确保你正在解析的json字符串的安全性。您应该查看类似于json-safe-parse或类似的库。

来自json-safe-parse npm页面:

JSON。parse非常棒,但是它在JavaScript上下文中有一个严重的缺陷:它允许重写继承的属性。如果解析JSON来自一个不受信任的源(例如:用户),并在其上调用您希望存在的函数,这就会成为一个问题。

我想提一下全局JSON对象的替代方案。 JSON。解析和JSON。stringify都是同步的,所以如果你想处理大对象,你可能想查看一些异步JSON模块。

看看:https://github.com/joyent/node/wiki/Modules#wiki-parsers-json

如果你需要用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