JSON

JavaScript Object Notation. The universal data exchange format.

What is JSON?

A text format for storing and transmitting data.

JavaScript Object

{
  name: "Alice",
  age: 28,
  hobbies: ["reading"]
}

JSON String

{
  "name": "Alice",
  "age": 28,
  "hobbies": ["reading"]
}

JSON rules:

  • Keys must be double-quoted strings
  • Values: strings, numbers, booleans, null, arrays, objects
  • No functions, undefined, comments, or trailing commas
  • Strings must use double quotes (not single)

JSON.stringify()

Convert a JavaScript value to a JSON string.

const user = { name: "Alice", age: 28 };

// Basic:
JSON.stringify(user);
// '{"name":"Alice","age":28}'

// Pretty-printed (2-space indent):
JSON.stringify(user, null, 2);
// {
//   "name": "Alice",
//   "age": 28
// }

// With replacer (filter properties):
JSON.stringify(user, ["name"]);
// '{"name":"Alice"}'
{"name":"Alice","age":28,"skills":["JS","React"]}

JSON.parse()

Convert a JSON string back to a JavaScript value.

const jsonString = '{"name":"Alice","age":28}';

const user = JSON.parse(jsonString);
console.log(user.name); // "Alice"
console.log(user.age);  // 28

// Always handle parse errors:
try {
  const data = JSON.parse(maybeInvalid);
} catch (error) {
  console.error("Invalid JSON:", error.message);
}

// With reviver (transform values):
JSON.parse(json, (key, value) => {
  if (key === "date") return new Date(value);
  return value;
});

⚠️ JSON.parse() throws on invalid JSON. Always wrap in try/catch when parsing user input or API responses.

Working with APIs

JSON is the standard format for web APIs.

// Fetch data from an API:
const response = await fetch("https://api.example.com/users");
const users = await response.json(); // auto-parses JSON

// Send JSON to an API:
await fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Alice",
    email: "alice@example.com",
  }),
});

Common flow:

JS Object→ stringify →JSON String→ network →JSON String→ parse →JS Object

Limitations

What JSON can't do.

// These are LOST during stringify:
const obj = {
  fn: () => "hello",     // functions → removed
  date: new Date(),      // Date → string
  undef: undefined,      // undefined → removed
  regex: /hello/g,       // RegExp → empty object {}
  inf: Infinity,         // Infinity → null
  nan: NaN,              // NaN → null
};

JSON.stringify(obj);
// {"date":"2024-01-15T...","regex":{},"inf":null,"nan":null}
// fn and undef are completely gone!
TypeIn JSON
string, number, boolean, null✓ Supported
array, object✓ Supported
undefined, function, Symbol✗ Removed
Date→ string (ISO format)
NaN, Infinity→ null

FAQ

Common questions about JSON.