![]() |
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: Table of Content 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.
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().
Output { name: 'GeeksforGeeks', CEO: 'Sandeep Jain' } Using Function ConstructorIn 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.
Output { name: 'GeeksforGeeks', CEO: 'Sandeep Jain' } |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |