How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
So yes it JSON. parse blocks. Parsing JSON is a CPU intensive task, and JS is single threaded. So the parsing would have to block the main thread at some point.
It`s ok to use it with some primitives like Numbers, Strings or Booleans. As you can see, you can just lose unsupported some data when copying your object in such a way. Moreover, JavaScript won`t even warn you about that, because calling JSON. stringify() with such data types does not throw any error.
You can simply use JSON.parse
.
The definition of the JSON
object is part of the ECMAScript 5 specification. node.js is built on Google Chrome's V8 engine, which adheres to ECMA standard. Therefore, node.js also has a global object JSON
[docs].
Note - JSON.parse
can tie up the current thread because it is a synchronous method. So if you are planning to parse big JSON objects use a streaming json parser.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With