How to Convert String to JSON in JavaScript?
Last Updated :
19 Apr, 2024
In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications.
Below are the approaches to converting string to JSON in JavaScript:
Using JSON.parse()
In this approach, we are using JSON.parse() in JavaScript to convert a JSON-formatted string (str) into a JavaScript object (res). This method parses the string according to JSON syntax.
Syntax:
JSON.parse( string, function(optional) )
Example: The below code will explain the use of the JSON.parse() method to convert a string in JSON.
JavaScript
let str = `{
"name": "GeeksforGeeks",
"CEO": "Sandeep Jain"
}`;
let res = JSON.parse(str);
console.log(res);
Output{ name: 'GeeksforGeeks', CEO: 'Sandeep Jain' }
Using eval()
In this approach, we are using eval() in JavaScript to directly evaluate and execute the JSON-formatted string (str) as JavaScript code, resulting in a JavaScript object (res) representing the parsed JSON data.
Syntax:
eval(str)
Example: The below code provides the implementation to convert string to JSON using eval().
JavaScript
let str = `{
"name": "GeeksforGeeks",
"CEO": "Sandeep Jain"
}`;
let res = eval('(' + str + ')');
console.log(res);
Output{ name: 'GeeksforGeeks', CEO: 'Sandeep Jain' }
Using Function Constructor
In this approach, we are using the Function Constructor in JavaScript to create a new function that returns the evaluated JSON-formatted string (str) as a JavaScript object (res).
Example: The below code example implements the Function() constructor which returns the Javascript Object.
JavaScript
let str = `{
"name": "GeeksforGeeks",
"CEO": "Sandeep Jain"
}`;
let res = new Function('return ' + str)();
console.log(res);
Output{ name: 'GeeksforGeeks', CEO: 'Sandeep Jain' }