English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node.js-When parsing json data, we can use the JSON.parse() function of the JavaScript engine.
There is little information about JSON data
Key:Value pairs are the foundation.
{} contains an element.
[] contains an element array.
An element can have multiplekey :value pairs.
Values can be simple values, such as numbers or strings, or elements or arrays.
Elements in an array can be accessed using an index
MultipleKey:Pairs or elements are separated by commas
The following example can help you use the JSON.parse() function and access elements from a JSON object.
// JSON Data var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}'; // Parse JSON var jsonParsed = JSON.parse(jsonData); // Access Element console.log(jsonParsed.persons[0].name);
Run nodejs-parse-Terminal output of json.js
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json.js John
We will read a File containing JSON data into a variable and then parse the data.
Consider the following JSON file sample.json
{ "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
// Import the file system module var fs = require('fs'); // Read the sample.json file fs.readFile('sample.json', // Callback function called when the file reading is completed function(err, data) { // JSON Data var jsonData = data; // Parse JSON var jsonParsed = JSON.parse(jsonData); // Access Element 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.
Run nodejs-parse-json-Terminal output of file.js
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json-file.js John's office phone number is 040-528-1258 Phil is from Kochi
In this Node.js tutorial- Node.js JSON File Parsing-We have learned to use the JSON.parse() function to parse JSON data from a variable or file with the help of an example Node.js program.