How to correctly use json.stringify() and json.parse() in JavaScript?
In JavaScript, the JSON.stringify() method is used to convert a JavaScript object to a JSON string, while the JSON.parse() method is used to convert a JSON string to a JavaScript object.
With the method JSON.stringify():
const obj = { name: "John", age: 30 };
const jsonStr = JSON.stringify(obj);
console.log(jsonStr); // {"name":"John","age":30}
Use the method JSON.parse()
const jsonStr = '{"name":"John","age":30}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // John
console.log(obj.age); // 30
Important note:
- The JSON.stringify() method can take optional parameters, such as the number of spaces used for string indentation. For example, JSON.stringify(obj, null, 2) will use 2 spaces for indentation in the generated JSON string.
- The JSON.parse() method will throw a SyntaxError if it encounters an invalid JSON format while parsing a JSON string. Therefore, it is essential to ensure that the string passed to the JSON.parse() method is a valid JSON format.
I hope this helps you!