JSON

Updated · 8 min read
mediumES2026javascriptjsonparsestringifyes2026interview

JSON (JavaScript Object Notation) is a text format for structured data, based on JavaScript's object and array literals. It is the standard way programs exchange data: web APIs send it, configuration files use it, browsers store it. JavaScript converts between JSON text and values with two functions: JSON.parse turns text into values, and JSON.stringify turns values into text. JSON looks almost exactly like JavaScript, but its rules are stricter, and it can't hold every JavaScript value.

In One Minute

  • JSON values: objects, arrays, strings (double quotes only), numbers, true, false and null.
  • JSON.parse(text) returns a value; invalid text throws a SyntaxError, so wrap it in try...catch.
  • JSON.stringify(value, replacer, space) returns text; space adds indentation.
  • JSON can't hold undefined, functions, symbols, NaN, Infinity, BigInt, Date objects, Maps or Sets as such.
  • A reviver (in parse) and a replacer (in stringify) transform values on the way in and out; ES2026 lets revivers read a number's exact source text.

JSON Syntax

student.json
{
  "name": "Navika Anamaneni",
  "grade": 9,
  "balance": 120.5,
  "enrolled": true,
  "scholarship": null,
  "guardian": { "name": "Srihitha Anamaneni", "city": "Dallas" },
  "payments": [120, 60]
}
RuleJSONJavaScript allows also
KeysMust be double-quoted strings: "name"Unquoted (name), single quotes
StringsDouble quotes onlySingle quotes, backticks
Trailing commasNot allowedAllowed
CommentsNot allowed// and /* */
ValuesObject, array, string, number, true, false, nullundefined, functions, NaN, dates...
NumbersNo leading +, no leading zeros, no hex, no NaN/InfinityAll of those

JSON is text. A JavaScript object and the JSON string describing it are different things: one is a value in memory, the other is characters you can send over a network or save in a file.

JSON.parse

Syntax

syntax.js
JSON.parse(text)
JSON.parse(text, reviver)

Example

parse.js▶ Try it
const text = '{"name":"Advitha","grade":9,"payments":[45,200],"guardian":null}';
const student = JSON.parse(text);
 
console.log(student.name, student.payments[1], student.guardian);
console.log(typeof text, typeof student);
console.log(JSON.parse("42"), JSON.parse('"hello"'), JSON.parse("[1, 2]"));
Output
Advitha 200 null
string object
42 hello [1, 2]

Any JSON value can be the top level, not just objects.

Invalid JSON Throws

invalid.js▶ Try it
const attempts = ["{name: 'Navika'}", '{"grade": 9,}', '{"a": 1} extra', ""];
 
for (const text of attempts) {
  try {
    JSON.parse(text);
  } catch (err) {
    console.log(err.name, "|", err.message);
  }
}
Output
SyntaxError | Expected property name or '}' in JSON at position 1 (line 1 column 2)
SyntaxError | Expected double-quoted property name in JSON at position 12 (line 1 column 13)
SyntaxError | Unexpected non-whitespace character after JSON at position 9 (line 1 column 10)
SyntaxError | Unexpected end of JSON input

Unquoted keys, single quotes, trailing commas, extra text and empty input are all errors. (These messages are V8's; other browsers word them differently.)

JSON.stringify

Syntax

syntax.js
JSON.stringify(value)
JSON.stringify(value, replacer, space)

Example

stringify.js▶ Try it
const payment = { name: "Srihitha", amount: 85, methods: ["card"], note: null };
 
console.log(JSON.stringify(payment));
console.log(JSON.stringify(payment, null, 2));
console.log(JSON.stringify(payment, ["name", "amount"]));
console.log(JSON.stringify("text"), JSON.stringify(42), JSON.stringify([1, "two"]));
Output
{"name":"Srihitha","amount":85,"methods":["card"],"note":null}
{
  "name": "Srihitha",
  "amount": 85,
  "methods": [
    "card"
  ],
  "note": null
}
{"name":"Srihitha","amount":85}
"text" 42 [1,"two"]

The third argument (space) indents the output for people to read. An array as the second argument keeps only the listed keys.

What JSON Can't Hold

JSON.stringify silently changes or drops values that JSON has no way to represent:

lossy.js▶ Try it
const data = {
  missing: undefined,
  greet() { return "hi"; },
  id: Symbol("id"),
  ratio: NaN,
  big: Infinity,
  due: new Date("2026-01-05T10:00:00Z"),
  tags: new Set(["paid"]),
  byGrade: new Map([[9, 400]]),
  list: [undefined, () => 1, NaN],
};
 
console.log(JSON.stringify(data));
 
try {
  JSON.stringify({ id: 10n });
} catch (err) {
  console.log(err.name);
}
Output
{"ratio":null,"big":null,"due":"2026-01-05T10:00:00.000Z","tags":{},"byGrade":{},"list":[null,null,null]}
TypeError
ValueBecomes
undefined, functions, symbols (as property values)Property dropped
undefined, functions, symbols (in arrays)null
NaN, Infinitynull
DateISO string (via its toJSON method); stays a string when parsed back
Map, Set{} (their contents are lost)
BigIntThrows TypeError
Circular referenceThrows TypeError

Replacers, toJSON and Revivers

A replacer function is called for every key and value during stringify; whatever it returns is written instead. An object's toJSON method controls how that object is stringified. A reviver function is called for every key and value during parse:

replacer-reviver.js▶ Try it
const account = {
  name: "Navika",
  balanceCents: 12050,
  due: new Date("2026-02-01T00:00:00Z"),
  tags: new Set(["sibling"]),
  password: "never-send-this",
};
 
const json = JSON.stringify(account, (key, value) => {
  if (key === "password") return undefined;
  if (value instanceof Set) return { $set: [...value] };
  return value;
});
console.log(json);
 
const restored = JSON.parse(json, (key, value) => {
  if (key === "due") return new Date(value);
  if (value && Array.isArray(value.$set)) return new Set(value.$set);
  return value;
});
console.log(restored.due instanceof Date, restored.tags.has("sibling"), "password" in restored);
Output
{"name":"Navika","balanceCents":12050,"due":"2026-02-01T00:00:00.000Z","tags":{"$set":["sibling"]}}
true true false

Explanation: the replacer dropped the password (returning undefined removes a property) and wrapped the Set in a marker object. Note that the due date had already been turned into a string by Date.prototype.toJSON before the replacer saw it. The reviver turned the date string back into a Date and the marker back into a Set.

Reading Exact Numbers: Source Text Access (ES2026)

JSON numbers are converted to JavaScript numbers, so large integers lose precision before your code ever sees them. ES2026 gives revivers a third argument, a context object whose source property holds the number's original text:

source-text.js▶ Try it
const text = '{"paymentId": 9007199254740993, "amount": 120.10}';
 
console.log(JSON.parse(text).paymentId);
 
const exact = JSON.parse(text, (key, value, context) => {
  if (key === "paymentId") return BigInt(context.source);
  return value;
});
console.log(String(exact.paymentId), exact.amount);
 
const out = JSON.stringify({ paymentId: JSON.rawJSON(exact.paymentId.toString()) });
console.log(out);
Output
9007199254740992
9007199254740993 120.1
{"paymentId":9007199254740993}

Explanation: plain parsing rounded the ID to ...992. The reviver read the exact digits from context.source and made a BigInt. In the other direction, JSON.rawJSON(text) inserts pre-formatted JSON text as-is, so a big number can be written without quotes or rounding. Both run in Node.js 26 and current Chrome (checked November 2026); in older runtimes, ask the API to send large IDs as strings.

JSON vs XML

XML is an older data format with tags, like HTML. You'll still meet it in some business systems, RSS feeds and SOAP web services:

The same data
JSON:  {"student": {"name": "Navika", "grade": 9}}
XML:   <student><name>Navika</name><grade>9</grade></student>
JSONXML
SizeSmallerLarger (closing tags)
In JavaScriptJSON.parse, values are ready to useDOMParser, then walk a DOM tree
Data typesNumbers, booleans, null, arraysEverything is text
Comments, attributes, namespacesNoYes
Typical use todayWeb APIs, configuration, storageDocuments, older enterprise systems, feeds

In Practice

The Fee Tracker exports and imports its data as JSON. Export uses a stable, readable format; import validates everything instead of trusting the file:

export-import.js▶ Try it
function exportData(students) {
  return JSON.stringify({ version: 1, exported: "2026-01-05", students }, null, 2);
}
 
function importData(text) {
  let data;
  try {
    data = JSON.parse(text);
  } catch {
    throw new Error("The file isn't valid JSON.");
  }
  if (data?.version !== 1 || !Array.isArray(data.students)) throw new Error("Unknown file format.");
  return data.students.filter((s) => typeof s.name === "string" && Number.isFinite(s.balance));
}
 
const file = exportData([{ name: "Navika", balance: 120 }, { name: "Advitha", balance: 45 }]);
console.log(file.split("\n").length, "lines");
console.log(importData(file).map((s) => s.name));
 
for (const bad of ["oops", '{"version": 2}']) {
  try {
    importData(bad);
  } catch (err) {
    console.log(err.message);
  }
}
Output
14 lines
['Navika', 'Advitha']
The file isn't valid JSON.
Unknown file format.

Common Mistakes

Single quotes or unquoted keys in JSON text. Only double quotes are valid.

Parsing without try...catch. Bad input crashes the program.

Expecting dates to survive a round trip. They come back as strings. Revive them.

Calling JSON.parse on something that's already an object. JSON.parse({}) converts the object to "[object Object]" first and throws. Parse only text.

Interview Corner

What values can't be represented in JSON?

undefined, functions and symbols (dropped from objects, null in arrays), NaN and Infinity (become null), BigInt (throws), circular references (throws). Dates become ISO strings, and Maps and Sets become {}. Use replacers, toJSON and revivers to handle them.

What is the difference between JSON and a JavaScript object?

JSON is a text serialization format with strict syntax (double-quoted keys and strings, no trailing commas, no comments, limited value types). A JavaScript object is an in-memory value. JSON.stringify serializes values to JSON text; JSON.parse deserializes text into new values.

Practice

Challenge: Write safeParse(text, fallback) that returns the parsed value, or fallback when the text is invalid or null/undefined.

Show solution
safe-parse.js▶ Try it
function safeParse(text, fallback) {
  if (text == null) return fallback;
  try {
    return JSON.parse(text);
  } catch {
    return fallback;
  }
}
 
console.log(safeParse('{"a": 1}', {}));
console.log(safeParse("{bad", {}));
console.log(safeParse(null, []));
Output
{ a: 1 }
{}
[]

Quick check: JSON

3 questions
1Which is valid JSON?
2What does JSON.stringify({ a: undefined, b: 1 }) return?
3What type is a date after JSON.parse(JSON.stringify({ d: new Date() })).d?

Key Takeaways

TaskCode
ParseJSON.parse(text)
Pretty printJSON.stringify(value, null, 2)
Keep some keysJSON.stringify(value, ["a", "b"])
Drop a keyreplacer returns undefined
Revive datesJSON.parse(text, (k, v) => k === "due" ? new Date(v) : v)
Exact big number(k, v, ctx) => BigInt(ctx.source)

Was this tutorial helpful?

Lesson 84 of 139