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


当前回答

这里的每个人都讲过JSON。所以我想说点别的。有一个伟大的模块连接许多中间件,使应用程序的开发更容易和更好。中间件之一是bodyParser。它可以解析JSON, html表单等。还有一个仅用于JSON解析的特定中间件noop。

看看上面的链接,它可能对你很有帮助。

其他回答

解析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。

JSON对象的定义是ECMAScript 5规范的一部分。node.js基于谷歌Chrome V8引擎,符合ECMA标准。因此,node.js也有一个全局对象JSON[docs]。

注- JSON。Parse会占用当前线程,因为它是一个同步方法。因此,如果您计划解析大型JSON对象,请使用流式JSON解析器。

一定要确保使用JSON。如果你的json中有一些损坏的数据,那么使用这段代码而不是简单的json,解析try catch块作为节点总是抛出一个意外错误。解析

try{
     JSON.parse(data)
}
catch(e){
   throw new Error("data is corrupted")
  }

正如在上面的答案中提到的,我们可以使用JSON.parse()将字符串解析为JSON 但是在解析之前,请确保解析正确的数据,否则可能会导致整个应用程序崩溃

这样使用是安全的

let parsedObj = {}
try {
    parsedObj = JSON.parse(data);
} catch(e) {
    console.log("Cannot parse because data is not is proper json format")
}

利用Lodash的attempt函数返回一个错误对象,可以用isError函数处理。

// Returns an error object on failure
function parseJSON(jsonString) {
   return _.attempt(JSON.parse.bind(null, jsonString));
}


// Example Usage
var goodJson = '{"id":123}';
var badJson = '{id:123}';
var goodResult = parseJSON(goodJson);
var badResult = parseJSON(badJson);

if (_.isError(goodResult)) {
   console.log('goodResult: handle error');
} else {
   console.log('goodResult: continue processing');
}
// > goodResult: continue processing

if (_.isError(badResult)) {
   console.log('badResult: handle error');
} else {
   console.log('badResult: continue processing');
}
// > badResult: handle error