How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?
You can simply use node.js is built on V8, which provides the global object Note - |
|||||||||||||||||||||
|
you can require .json files.
For example if you have a
or (file extension can be omitted):
note that |
|||||||||||||||||||||
|
use the JSON object:
|
|||||||||||||||||||||
|
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 |
|||||||||||||
|
You can use
Parsing a string containing JSON data
Parsing a file containing JSON dataYou'll have to do some file operations with
Then you can read the data asynchronously/synchronously. Asynchronous version
Synchronous version
|
Another example of JSON.parse :
|
|||||
|
Include the
For more info on 'fs' library , refer the documentation at http://nodejs.org/api/fs.html |
|||||||||
|
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:
OR in "async style"
|
|||||
|
That's all. |
||||
|
Parsing a JSON stream? Use
|
|||
|
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:
or to use the global JSON object to parse a string value into an object:
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... |
|||||
|
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. |
|||
|
My solution:
|
||||
|
|
|||
|
JSON.parse will not ensure safety of json string you are parsing. You should look at a library like json-safe-parse or a similar library. From json-safe-parse npm page:
|
|||
|
It's simple, you can convert JSON to string using |
|||||||||
|