Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON using Node.js? [closed]

How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?

like image 306
Tikhon Jelvis Avatar asked Apr 20 '11 07:04

Tikhon Jelvis


People also ask

Which method is used to parse JSON in node JS?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

Is JSON parse blocking or not?

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.

Is it bad to use JSON Stringify?

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.


2 Answers

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.

like image 117
Felix Kling Avatar answered Sep 28 '22 17:09

Felix Kling


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.

like image 38
eliocs Avatar answered Sep 28 '22 17:09

eliocs