How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?
相关问题
- Is there a limit to how many levels you can nest i
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
- StackExchange API - Deserialize Date in JSON Respo
Include the
node-fs
library.For more info on 'fs' library , refer the documentation at http://nodejs.org/api/fs.html
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
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
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"
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.