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 11:01
var array={
    Action: 'Login',
    ErrorCode: 3,
    Detail: 'Your account not found.'
};
var http=require('http'),
    PORT=8789,
    server=function(req,res){
        res.writeHead(200,{'Content-Type':'application/json'});

        // JSON
        res.end(JSON.stringify(array));
    }

http.createServer(server).listen(PORT);
console.log('Server started.');
查看更多
情到深处是孤独
3楼-- · 2018-12-31 11:01

No further modules need to be required.
Just use
var parsedObj = JSON.parse(yourObj);
I don think there is any security issues regarding this

查看更多
长期被迫恋爱
4楼-- · 2018-12-31 11:01

It's simple, you can convert JSON to string using JSON.stringify(json_obj), and convert string to JSON using JSON.parse("your json string").

查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 11:03

You can simply use JSON.parse.

The definition of the JSON object is part of the ECMAScript 5 specification. node.js is built on Google Chrome's V8 engine, which adheres to ECMA standard. Therefore, node.js also has a global object JSON[docs].

Note - JSON.parse can tie up the current thread because it is a synchronous method. So if you are planning to parse big JSON objects use a streaming json parser.

查看更多
牵手、夕阳
6楼-- · 2018-12-31 11:04

Leverage Lodash's attempt function to return an error object, which you can handle with the isError function.

// 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
查看更多
泛滥B
7楼-- · 2018-12-31 11:05

Parsing a JSON stream? Use 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

查看更多
登录 后发表回答