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:44

I'd like to mention that there are alternatives to the global JSON object. JSON.parse and JSON.stringify are both synchronous, so if you want to deal with big objects you might want to check out some of the asynchronous JSON modules.

Have a look: https://github.com/joyent/node/wiki/Modules#wiki-parsers-json

查看更多
几人难应
3楼-- · 2018-12-31 10:45

you can require .json files.

var parsedJSON = require('./file-name');

For example if you have a config.json file in the same directory as your source code file you would use:

var config = require('./config.json');

or (file extension can be omitted):

var config = require('./config');

note that require is synchronous and only reads the file once, following calls return the result from cache

Also note You should only use this for local files under your absolute control, as it potentially executes any code within the file.

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 10:45

You can use JSON.parse().

You should be able to use the JSON object on any ECMAScript 5 compatible JavaScript implementation. And V8, upon which Node.js is built is one of them.


Parsing a string containing JSON data

var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);

Parsing a file containing JSON data

You'll have to do some file operations with fs module.

Asynchronous version

var fs = require('fs');

fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
    if (err) throw err; // we'll not consider error handling for now
    var obj = JSON.parse(data);
});

Synchronous version

var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));

You wanna use require? Think again!

You can sometimes use require:

var obj = require('path/to/file.json');

But, I do not recommend this for several reasons:

Note: If you're using a JSON file to store sensitive information (e.g. passwords), that's the wrong way to do it. See how Heroku does it: https://devcenter.heroku.com/articles/config-vars#setting-up-config-vars-for-a-deployed-application. Find out how your platform does it, and use process.env to retrieve the config vars from within the code.

  1. require is synchronous. If you have a very big JSON file, it will choke your event loop. You really need to use JSON.parse with fs.readFile.
  2. require will read the file only once. Subsequent calls to require for the same file will return a cached copy. Not a good idea if you want to read a .json file that is continuously updated. You could use a hack. But at this point, it's easier to simply use fs.
  3. If your file does not have a .json extension, require will not treat the contents of the file as JSON.

Seriously! Use JSON.parse.


load-json-file module

If you are reading large number of .json files, (and if you are extremely lazy), it becomes annoying to write boilerplate code every time. You can save some characters by using the load-json-file module.

const loadJsonFile = require('load-json-file');

Asynchronous version

loadJsonFile('/path/to/file.json').then(json => {
    // `json` contains the parsed object
});

Synchronous version

let obj = loadJsonFile.sync('/path/to/file.json');

Parsing JSON from streams

If the JSON content is streamed over the network, you need to use a streaming JSON parser. Otherwise it will tie up your processor and choke your event loop until JSON content is fully streamed.

There are plenty of packages available in NPM for this. Choose what's best for you.


Error Handling/Security

If you are unsure if whatever that is passed to JSON.parse() is valid JSON, make sure to enclose the call to JSON.parse() inside a try/catch block. A user provided JSON string could crash your application, and could even lead to security holes. Make sure error handling is done if you parse externally-provided JSON.

查看更多
琉璃瓶的回忆
5楼-- · 2018-12-31 10:45
JSON.parse("your string");

That's all.

查看更多
冷夜・残月
6楼-- · 2018-12-31 10:46

This had to be shouted at me: it only works for .json files.

If the file ending is different this does not work!

查看更多
公子世无双
7楼-- · 2018-12-31 10:46

Use this to be on the safe side

var data = JSON.parse(Buffer.concat(arr).toString());

查看更多
登录 后发表回答