How to work with JSON data (parsing and stringifying) in JavaScript?

In JavaScript, you can use the built-in JSON object to parse and stringify JSON data.

To parse JSON data:

  1. Use the JSON.parse() method to convert a JSON string into a JavaScript object.
const jsonString = '{"name":"John", "age":30, "city":"New York"}'; const obj = JSON.parse(jsonString); console.log(obj.name); // Output: John console.log(obj.age); // Output: 30 console.log(obj.city); // Output: New York

To stringify JavaScript objects into JSON:

  1. Use the JSON.stringify() method to convert a JavaScript object into a JSON string.
const obj = { name: "John", age: 30, city: "New York" }; const jsonString = JSON.stringify(obj); console.log(jsonString); // Output: {"name":"John","age":30,"city":"New York"}

Note: JSON.stringify() can also take additional parameters to specify which object properties to include or exclude, and to format the output JSON string.

It's important to keep in mind that JSON data should follow a specific format, with keys enclosed in double quotes and values either as strings, numbers, booleans, null, arrays, or objects.

Additionally, ensure that the JSON string is well-formed and valid. Otherwise, parsing will throw an error.