Node.js Parse JSON
Node.js Parse JSON – For parsing JSON data in Node.js, we can use JSON.parse() function of JavaScript Engine.
Little information to use JSON Data
- key:value is the building block.
- { } contains an element.
- [ ] contains an array of elements.
- An element can have multiplekey:value pairs.
- Value can be a simple value like number or string etc., or an element or an array.
- Elements in an Array could be accessed using index
- Multiplekey:value pairs or elements are separated by comma
A Simple Example Node.js JSON Parsing Program
Following example helps you to use JSON.parse() function and access the elements from JSON Object.
1 2 3 4 5 6 7 8 | // json data var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}'; // parse json var jsonParsed = JSON.parse(jsonData); // access elements console.log(jsonParsed.persons[0].name); |
1 2 | arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json.js John |
Example – Node.js Parse JSON File
We shall read a File containing JSON data to a variable and parse that data.
Consider following JSON File, sample.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | { "persons": [{ "name": "John", "city": "Kochi", "phone": { "office": "040-528-1258", "home": "9952685471" } }, { "name": "Phil", "city": "Varkazha", "phone": { "office": "040-528-8569", "home": "7955555472" } } ] } |
Node.js JSON File Parsing Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // include file system module var fs = require('fs'); // read file sample.json file fs.readFile('sample.json', // callback function that is called when reading file is done function(err, data) { // json data var jsonData = data; // parse json var jsonParsed = JSON.parse(jsonData); // access elements console.log(jsonParsed.persons[0].name + "'s office phone number is " + jsonParsed.persons[0].phone.office); console.log(jsonParsed.persons[1].name + " is from " + jsonParsed.persons[0].city); }); |
Run the above Node.js program.
1 2 3 | arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json-file.js John's office phone number is 040-528-1258 Phil is from Kochi |
Conclusion :
In this Node.js Tutorial – Node.js JSON File Parsing – we have learnt to parse JSON data from a variable or file using JSON.parse() function with the help of example Node.js programs.