Convert String to JSON Using Function Constructor
In this approach, we will use Function() constructor which creates a function that returns a Javascript Object parsed to it.
Example: The below code example implements the Function() constructor which returns the Javascript Object.
const jsonString: string = `{
"Platform": "w3wiki",
"type": "EdTech"
}`;
const jsonObject =
new Function('return ' + jsonString)();
console.log(jsonObject);
Output:
{
Platform: 'w3wiki',
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