How can I convert a JSON string to an object in JavaScript?
Rashid D
rashid d profile pic

To convert a JSON string to an object in JavaScript, you can use theJSON.parse() method. Here's a step-by-step guide on how to achieve this: 1. Create a JSON string:

1
2
3

   const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
   

2. Use theJSON.parse() method: TheJSON.parse() method parses a JSON string and returns the corresponding JavaScript object. Pass the JSON string as an argument to this method to convert it to an object.

1
2
3
4
5

   const jsonObject = JSON.parse(jsonString);
   console.log(jsonObject);
   // Output: {name: "John", age: 30, city: "New York"}
   

In this example, the JSON string is converted to a JavaScript object. 3. Access the properties of the object: Once the JSON string is converted to an object, you can access its properties using dot notation or square bracket notation.

1
2
3
4
5

   console.log(jsonObject.name);  // Output: "John"
   console.log(jsonObject.age);   // Output: 30
   console.log(jsonObject.city);  // Output: "New York"
   

In this example, thename,age, andcity properties of the object are accessed and printed to the console. It's important to note that the JSON string must be in valid JSON format forJSON.parse() to work correctly. Ensure that the string is properly formatted with double quotes around the property names and string values. By following these steps, you can convert a JSON string to an object in JavaScript using theJSON.parse() method. This allows you to work with the data in its JavaScript object form, enabling you to access and manipulate its properties as needed.