Syntax
JSON.stringify(value)
JSON.parse(jsonString)Examples
Basic Stringify and Parse
Converting between JavaScript objects and JSON strings.
const user = { name: "Alice", age: 25, active: true };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Alice","age":25,"active":true}'
const parsedBack = JSON.parse(jsonString);
console.log(parsedBack.name); // "Alice"
console.log(typeof parsedBack); // "object"Pretty-Printing with Indentation
Formatting JSON output for readability using the third argument.
const data = { name: "Bob", roles: ["admin", "editor"] };
console.log(JSON.stringify(data, null, 2));
// {
// "name": "Bob",
// "roles": [
// "admin",
// "editor"
// ]
// }What Gets Dropped or Converted
JSON.stringify() cannot represent every JavaScript value.
const data = {
name: "Alice",
greet: function() { console.log("hi"); }, // dropped entirely
unset: undefined, // dropped entirely
missing: null, // kept as null
when: new Date() // converted to an ISO string
};
console.log(JSON.stringify(data));
// functions and undefined values disappear from the outputBest practices
- Always wrap JSON.parse() in a try/catch, since it throws an error on invalid or malformed JSON
- Use the third argument of JSON.stringify() (a number of spaces) for human-readable, indented output during debugging
- Remember functions, undefined, and symbols are silently omitted during stringification - do not rely on them surviving a round trip
- Be aware that Dates become strings after JSON.stringify(), and will need to be manually converted back with new Date() after parsing
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification