Open In App

How to Parse JSON Data in JavaScript ?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It is easy for machines to parse and generate it. In JavaScript, parsing JSON data is a common task when dealing with APIs or exchanging data between the client and server.

Using JSON.parse() Method

This is the recommended and safest way to parse JSON data in JavaScript. The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

Syntax:

let jsonObject = JSON.parse(jsonString);

Example: Parsing the Person JSON data using the JSON parse() method.

JavaScript
let jsonString = '{"name": "ABC", "age": 30}';
let jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name);
console.log(jsonObject.age);

Output
ABC
30

Using eval() Function

Although it is not recommended due to security concerns, you can use the eval() function to parse JSON data. However, this method executes the code passed to it, which can pose security risks if the JSON data is from an untrusted source.

Syntax:

let jsonObject = eval('(' + jsonString + ')');

Example: Parsing the Person JSON data using the eval() method.

JavaScript
let jsonString = '{"name": "ABC", "age": 30}';
let jsonObject = eval('(' + jsonString + ')');
console.log(jsonObject.name); 
console.log(jsonObject.age);

Output
ABC
30

Using new Function() Constructor

Similar to eval(), you can also use the new Function() constructor to parse JSON data. However, this method also executes the code passed to it, making it susceptible to security vulnerabilities.

Syntax:

let parseJson = new Function('return ' + jsonString + ';');
let jsonObject = parseJson();

Example: Parsing the Person JSON data using the new Function() method.

JavaScript
let jsonString = '{"name": "ABC", "age": 30}';
let parseJson = new Function('return ' + jsonString + ';');
let jsonObject = parseJson();
console.log(jsonObject.name);
console.log(jsonObject.age);

Output
ABC
30

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads