Skip to content
  • JSON · JavaScript

JSON

LearnViaNotes @learnvianotes· 2 min read

JSON is a text format for data, borrowed from JavaScript literal syntax. JSON.stringify serialises, JSON.parse deserialises — each with a hook for customisation.

JSON vs JavaScript objects

JSONJavaScript object literal
Keys must be double-quoted stringsKeys can be bare identifiers
Strings in double quotes only'single', "double" and backtick templates
Values: string, number, boolean, null, object, arrayAlso functions, undefined, symbols, BigInt, Date, Map…
No trailing commas, no commentsTrailing commas allowed

stringify

JavaScript
const data = {
  name: "Asha",
  tags: ["js", "node"],
  born: new Date(Date.UTC(1995, 11, 4)),
  skip: undefined,
  fn() {},
  sym: Symbol("s"),
  nan: NaN,
  inf: Infinity,
};
console.log(JSON.stringify(data));
console.log(JSON.stringify([undefined, () => {}, NaN]));
console.log(JSON.stringify({ a: 1, b: [1, 2] }, null, 2));
Output
{"name":"Asha","tags":["js","node"],"born":"1995-12-04T00:00:00.000Z","nan":null,"inf":null}
[null,null,null]
{
  "a": 1,
  "b": [
    1,
    2
  ]
}

Replacer, toJSON and reviver

JavaScript
const user = { name: "Ravi", password: "hunter2", age: 30 };
console.log(JSON.stringify(user, ["name", "age"]));
console.log(JSON.stringify(user, (k, v) => (k === "password" ? undefined : v)));

class Money {
  constructor(cents) { this.cents = cents; }
  toJSON() { return `$${(this.cents / 100).toFixed(2)}`; }
}
console.log(JSON.stringify({ total: new Money(1999) }));

const text = '{"when":"2024-01-15T10:00:00.000Z","n":1}';
const parsed = JSON.parse(text, (k, v) => (k === "when" ? new Date(v) : v));
console.log(parsed.when instanceof Date, parsed.when.getUTCFullYear());
Output
{"name":"Ravi","age":30}
{"name":"Ravi","age":30}
{"total":"$19.99"}
true 2024

Errors

JavaScript
try {
  JSON.parse("{name: 'x'}");
} catch (e) {
  console.log(e.name);
}
const a = { name: "loop" };
a.self = a;
try {
  JSON.stringify(a);
} catch (e) {
  console.log(e.message.split("\n")[0]);
}
try {
  JSON.stringify({ n: 1n });
} catch (e) {
  console.log(e.message);
}
Output
SyntaxError
Converting circular structure to JSON
Do not know how to serialize a BigInt

Is JSON.parse(JSON.stringify(obj)) a good deep clone?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report