PASSWORD RESET

Your destination for complete Tech news

How to convert a JSON string into a Javascript object?

265 0
< 1 min read

To convert a JSON string into a JavaScript object, you can use the JSON.parse() method. This method parses a JSON string and returns a JavaScript object constructed from the JSON data.

Here is an example of how to use JSON.parse() to convert a JSON string into a JavaScript object:

let jsonString = '{"name":"John", "age":30, "city":"New York"}';
let obj = JSON.parse(jsonString);

console.log(obj.name);  // "John"
console.log(obj.age);   // 30
console.log(obj.city);  // "New York"

In this example, the JSON.parse() method takes the JSON string as an argument and returns a JavaScript object with properties name, age, and city. The object properties can then be accessed using dot notation or array notation.

Note that JSON.parse() can throw a SyntaxError if the JSON string is not properly formatted. It is a good idea to wrap the call to JSON.parse() in a try-catch block to handle this error.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.