javascript tutorial - [Solved-5 Solutions] JSON using Node.js - javascript - java script - javascript array
Problem:
How to parse JSON using Node.js ?
Solution 1:
- node.js is built on V8, which provides the global object JSON[docs]. The definition of the JSONobject is part of the ECMAScript 5 specification.
- Note - JSON.parse can tie up the current thread because it is a synchronous method
Solution 2:
we can require .json files.
var parsedJSON = require('./file-name');
click below button to copy the code. By JavaScript tutorial team
For example if we have a config.json
file in the same directory as your source code file we would use:
var config = require('./config.json');
click below button to copy the code. By JavaScript tutorial team
or (file extension can be omitted):
var config = require('./config');
click below button to copy the code. By JavaScript tutorial team
Note that require is synchronous and only reads the file once, following calls return the result from cache
Solution 3:
Parsing a string containing JSON data
var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);
click below button to copy the code. By JavaScript tutorial team
Parsing a file containing JSON data
we'll have to do some file operations with fs module.
Asynchronous version
var fs = require('fs');
fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
if (err) throw err; // we'll not consider error handling for now
var obj = JSON.parse(data);
});
click below button to copy the code. By JavaScript tutorial team
Synchronous version
var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));
click below button to copy the code. By JavaScript tutorial team
Solution 4:
use the JSON object:
JSON.parse(str);
click below button to copy the code. By JavaScript tutorial team
Solution 5:
var fs = require('fs');
var file = __dirname + '/config.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.dir(data);
});