How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?
Join them; it only takes a minute:
|
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 Also note You should only use this for local files under your absolute control, as it potentially executes any code within the file. |
|||||||||||||||||||||
|
You can use You should be able to use the Parsing a string containing JSON data
Parsing a file containing JSON dataYou'll have to do some file operations with Asynchronous version
Synchronous version
You wanna use
|
|
|||
|
@natario: We are talking about server-side JS here. Suppose someone is parsing user-supplied JSON. If the assumption is that the JSON is always well formed, an attacker can send some malformed JSON to trigger an error, which if spilled to the client side, may reveal vital information about the system. Or if the JSON was both malformed and contained some text with
<script>... , and the error is spilled to the client side, you have an XSS bug right there. Therefore IMO it's important to handle JSON errors right where you parse it.
– Krumia
Oct 28 '16 at 11:11
|
||
|
|||
|
@Krumia: Are you talking about security holes in user-supplied JSON that was added via the require statement? I think var config = require(jsonFile); will be literally as "user-supplied" as any other source code, correct? It would be handled at source compile-time.
– Nick Steele
Jan 3 at 23:19
|
||
|
@NickSteele: However, I changed "this is not recommended" to "I do not recommend". I hope you are happy now.
– Krumia
Jan 9 at 3:48
|
use the JSON object:
|
|||||||||||||||||||||
|
I'd like to mention that there are alternatives to the global JSON object.
Have a look: https://github.com/joyent/node/wiki/Modules#wiki-parsers-json |
|||||||||||||||||
|
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"
|
|||||
|
Parsing a JSON stream? Use
|
|||
|
That's all. |
||||
|
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:
|
|||
|
Just to make this as complicated as possible, and bring in as many packages as possible...
This lets you do:
Or if you're using async/await:
The advantage over just using |
||||
|
Just want to complete the answer (as I struggled with it for a while), want to show how to access the json information, this example shows accessing Json Array:
|
|||
|
|
|||
|
Leverage Lodash's attempt function to return an error object, which you can handle with the isError function.
|
|||||
|
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 you want to add some comments in your JSON and allow trailing commas you might want use below implemention:
Note that it might not work well if you have something like |
|||
|
Using JSON for your configuration with Node.js? Read this and get your configuration skills over 9000...
Proper applications come in 3+ layers of configuration:
Most developers treat their server and app config as if it can change. It can't. You can layer changes from higher layers on top of each other, but you're modifying base requirements. Some things need to exist! Make your config act like it's immutable, because some of it basically is, just like your source code. Failing to see that lots of your stuff isn't going to change after startup leads to anti-patterns like littering your config loading with try/catch blocks, and pretending you can continue without your properly setup application. You can't. If you can, that belongs in the community/user config layer, not the server/app config layer. You're just doing it wrong. The optional stuff should be layered on top when the application finishes it's bootstrap. Stop banging your head against the wall: Your config should be ultra simple. Take a look at how easy it is to setup something as complex as a protocol-agnostic and datasource-agnostic service framework using a simple json config file and simple app.js file... container-config.js...
index.js... (the engine that powers everything)
app.js... (the code that powers your protocol-agnostic and data-source agnostic service)
Using this pattern, you can now load community and user config stuff on top of your booted app, dev ops is ready to shove your work into a container and scale it. You're read for multitenant. Userland is isolated. You can now separate the concerns of which service protocol you're using, which database type you're using, and just focus on writing good code. Because you're using layers, you can rely on a single source of truth for everything, at any time (the layered config object), and avoid error checks at every step, worrying about "oh crap, how am I going to make this work without proper config?!?". |
||||
|
It's simple, you can convert JSON to string using |
|||||||||
|
|
|||||
|
This had to be shouted at me: it only works for If the file ending is different this does not work! |
|||||
|