JSON
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,falseandnull. JSON.parse(text)returns a value; invalid text throws aSyntaxError, so wrap it intry...catch.JSON.stringify(value, replacer, space)returns text;spaceadds indentation.- JSON can't hold
undefined, functions, symbols,NaN,Infinity,BigInt,Dateobjects, Maps or Sets as such. - A reviver (in
parse) and a replacer (instringify) transform values on the way in and out; ES2026 lets revivers read a number's exact source text.
JSON Syntax
{
"name": "Navika Anamaneni",
"grade": 9,
"balance": 120.5,
"enrolled": true,
"scholarship": null,
"guardian": { "name": "Srihitha Anamaneni", "city": "Dallas" },
"payments": [120, 60]
}| Rule | JSON | JavaScript allows also |
|---|---|---|
| Keys | Must be double-quoted strings: "name" | Unquoted (name), single quotes |
| Strings | Double quotes only | Single quotes, backticks |
| Trailing commas | Not allowed | Allowed |
| Comments | Not allowed | // and /* */ |
| Values | Object, array, string, number, true, false, null | undefined, functions, NaN, dates... |
| Numbers | No leading +, no leading zeros, no hex, no NaN/Infinity | All 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
JSON.parse(text)
JSON.parse(text, reviver)Example
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]"));Advitha 200 null
string object
42 hello [1, 2]Any JSON value can be the top level, not just objects.
Invalid JSON Throws
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);
}
}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 inputUnquoted 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
JSON.stringify(value)
JSON.stringify(value, replacer, space)Example
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"]));{"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:
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);
}{"ratio":null,"big":null,"due":"2026-01-05T10:00:00.000Z","tags":{},"byGrade":{},"list":[null,null,null]}
TypeError| Value | Becomes |
|---|---|
undefined, functions, symbols (as property values) | Property dropped |
undefined, functions, symbols (in arrays) | null |
NaN, Infinity | null |
Date | ISO string (via its toJSON method); stays a string when parsed back |
Map, Set | {} (their contents are lost) |
BigInt | Throws TypeError |
| Circular reference | Throws 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:
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);{"name":"Navika","balanceCents":12050,"due":"2026-02-01T00:00:00.000Z","tags":{"$set":["sibling"]}}
true true falseExplanation: 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:
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);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:
JSON: {"student": {"name": "Navika", "grade": 9}}
XML: <student><name>Navika</name><grade>9</grade></student>| JSON | XML | |
|---|---|---|
| Size | Smaller | Larger (closing tags) |
| In JavaScript | JSON.parse, values are ready to use | DOMParser, then walk a DOM tree |
| Data types | Numbers, booleans, null, arrays | Everything is text |
| Comments, attributes, namespaces | No | Yes |
| Typical use today | Web APIs, configuration, storage | Documents, 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:
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);
}
}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
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, []));{ a: 1 }
{}
[]Key Takeaways
| Task | Code |
|---|---|
| Parse | JSON.parse(text) |
| Pretty print | JSON.stringify(value, null, 2) |
| Keep some keys | JSON.stringify(value, ["a", "b"]) |
| Drop a key | replacer returns undefined |
| Revive dates | JSON.parse(text, (k, v) => k === "due" ? new Date(v) : v) |
| Exact big number | (k, v, ctx) => BigInt(ctx.source) |
Was this tutorial helpful?