Convert String to JSON Using eval()
In this approach, we will use eval() function which is a global function in JavaScript that evaluates a string of JavaScript code in the context from which it’s called.
Syntax:
eval(codeString)
Example: The below code provides the implementation to convert string to JSON using eval().
const jsonString: string = `{
"name": "GFG",
"est": 2009,
"type": "EdTech"
}`;
const jsonObject =
eval('(' + jsonString + ')');
console.log(jsonObject);
Output:
{
name: 'GFG',
est: 2009,
type: 'EdTech'
}
How to Convert String to JSON in TypeScript ?
Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission.
Below are the approaches to converting string to JSON in TypeScript:
Table of Content
- Convert String to JSON Using JSON.parse()
- Convert String to JSON Using eval()
- Convert String to JSON Using Function Constructor
- Using JSON.parse() with reviver function for date parsing
Contact Us