Convert String to JSON Using JSON.parse()
In this approach, we will make use of JSON.parse() function which parses a JSON string and converts it into a JavaScript object. It takes a single argument, which is a valid JSON-formatted string.
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.
const jsonString: string =
`{
"name": "w3wiki",
"est": "2009",
"CEO": "Sandeep Jain"
}`;
const jsonObject =
JSON.parse(jsonString);
console.log(jsonObject);
console.log(jsonObject.name);
Output:
{
name: "w3wiki",
est: "2009",
CEO: "Sandeep Jain"
}
name: "w3wiki"
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