Codectionary / Developer documentation / JavaScript

JSON: stringify() and parse()

JSON (JavaScript Object Notation) is a text format for representing structured data, widely used for APIs and configuration. JSON.stringify() converts a JavaScript value into a JSON string, and JSON.parse() converts a JSON string back into a JavaScript value. Functions, undefined, and symbols are silently dropped or converted during stringification.

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 output

Best 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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation