Node.js Parse JSON

Node.js Parse JSON – For parsing JSON data in Node.js, we can use JSON.parse() function of JavaScript Engine.

In this tutorial, we will learn how to parse given JSON string using JSON.parse() function, with example programs.

About JSON

  • 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
ADVERTISEMENT

Example 1 – Node.js JSON Parsing

In this example, we will use JSON.parse() function to parse the string jsonData. Also, we will access the elements from JSON Object using DOT operator.

nodejs-parse-json.js

// 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);

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json.js 
John

Example 2 – Node.js Parse JSON File

In this example, we shall read a File containing JSON data to a variable and parse that data.

Consider following JSON File. We shall read this file as string to a variable.

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"
			}
		}
	]
}

nodejs-parse-json-file.js

// 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);
});

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

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.