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

Include the node-fs library.

var fs = require("fs");
var file = JSON.parse(fs.readFileSync("./PATH/data.json", "utf8"));

For more info on 'fs' library , refer the documentation at http://nodejs.org/api/fs.html

查看更多
还给你的自由
3楼-- · 2018-12-31 10:49

Always be sure to use JSON.parse in try catch block as node always throw an Unexpected Error if you have some corrupted data in your json so use this code instead of simple JSON.Parse

try{
     JSON.parse(data)
}
catch(e){
   throw new Error("data is corrupted")
  }
查看更多
浅入江南
4楼-- · 2018-12-31 10:50

If the JSON source file is pretty big, may want to consider the asynchronous route via native async / await approach with Node.js 8.0 as follows

const fs = require('fs')

const fsReadFile = (fileName) => {
    fileName = `${__dirname}/${fileName}`
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, 'utf8', (error, data) => {
            if (!error && data) {
                resolve(data)
            } else {
                reject(error);
            }
        });
    })
}

async function parseJSON(fileName) {
    try {
        return JSON.parse(await fsReadFile(fileName));
    } catch (err) {
        return { Error: `Something has gone wrong: ${err}` };
    }
}

parseJSON('veryBigFile.json')
    .then(res => console.log(res))
    .catch(err => console.log(err))
查看更多
何处买醉
5楼-- · 2018-12-31 10:54

Since you don't know that your string is actually valid, I would put it first into a try catch. Also since try catch blocks are not optimized by node, i would put the entire thing into another function:

function tryParseJson(str) {
    try {
        return JSON.parse(str);
    } catch (ex) {
        return null;
    }
}

OR in "async style"

function tryParseJson(str, callback) {
    process.nextTick(function () {
      try {
          callback(null, JSON.parse(str));
      } catch (ex) {
          callback(ex)
      }
    })
}
查看更多
深知你不懂我心
6楼-- · 2018-12-31 10:54

as other answers here have mentioned, you probably want to either require a local json file that you know is safe and present, like a configuration file:

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

or to use the global JSON object to parse a string value into an object:

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

note that when you require a file the content of that file is evaluated, which introduces a security risk in case it's not a json file but a js file.

here, i've published a demo where you can see both methods and play with them online (the parsing example is in app.js file - then click on the run button and see the result in the terminal): http://staging1.codefresh.io/labs/api/env/json-parse-example

you can modify the code and see the impact...

查看更多
深知你不懂我心
7楼-- · 2018-12-31 10:54

Everybody here has told about JSON.parse, so I thought of saying something else. There is a great module Connect with many middleware to make development of apps easier and better. One of the middleware is bodyParser. It parses JSON, html-forms and etc. There is also a specific middleware for JSON parsing only noop.

Take a look at the links above, it might be really helpful to you.

查看更多
登录 后发表回答