JavaScript JSON
JSON (JavaScript Object Notation) is a text format for storing and exchanging data. It looks almost exactly like JavaScript object and array literals, which is why it became the standard way for web servers and browsers to talk to each other. APIs send JSON, configuration files (like package.json) are JSON, and browser storage holds JSON strings.
What JSON looks like
{
"name": "Ana",
"age": 29,
"admin": false,
"skills": ["js", "css"],
"address": { "city": "Lisbon", "zip": null }
}JSON is stricter than JavaScript:
| Rule | JSON | JavaScript object literal |
|---|---|---|
| Keys | must be in double quotes | quotes optional |
| Strings | double quotes only | 'single', "double", `back` |
| Trailing commas | ❌ not allowed | ✅ allowed |
| Comments | ❌ not allowed | ✅ allowed |
| Values | string, number, boolean, null, object, array |
anything, including functions, undefined, dates |
JSON.stringify — object to text
const user = {
name: "Ana",
age: 29,
skills: ["js", "css"],
address: { city: "Lisbon" },
};
const text = JSON.stringify(user);
console.log(text);
console.log(typeof text);
console.log(JSON.stringify(user, null, 2)); // pretty-printed, 2-space indent
console.log(JSON.stringify(user, ["name", "age"])); // only these keys{"name":"Ana","age":29,"skills":["js","css"],"address":{"city":"Lisbon"}}
string
{
"name": "Ana",
"age": 29,
"skills": [
"js",
"css"
],
"address": {
"city": "Lisbon"
}
}
{"name":"Ana","age":29}
JSON.parse — text to object
JSON.parse turns a JSON string back into real JavaScript values you can work with:
const response = '{"id": 42, "title": "Learn JSON", "done": false, "tags": ["study"]}';
const task = JSON.parse(response);
console.log(task.title);
console.log(task.tags[0]);
task.done = true;
console.log(task);Learn JSON
study
{ id: 42, title: 'Learn JSON', done: true, tags: [ 'study' ] }
Invalid JSON throws a SyntaxError, so wrap parsing of untrusted text in try…catch:
const inputs = ['{"ok": true}', "{'ok': true}", '{"list": [1, 2,]}', "42", '"text"'];
for (const input of inputs) {
try {
console.log("parsed:", JSON.parse(input));
} catch (err) {
console.log("invalid:", input);
}
}parsed: { ok: true }
invalid: {'ok': true}
invalid: {"list": [1, 2,]}
parsed: 42
parsed: text
What gets lost
JSON.stringify can't represent everything. Functions, undefined and symbols are skipped in objects (and become null in arrays); NaN and Infinity become null; dates become ISO strings; Maps and Sets become {}; BigInts throw:
const tricky = {
when: new Date("2025-03-14T10:00:00Z"),
missing: undefined,
greet() {},
ratio: NaN,
list: [undefined, () => 1, Infinity],
tags: new Set(["a"]),
};
console.log(JSON.stringify(tricky));
const back = JSON.parse(JSON.stringify(tricky));
console.log(typeof back.when); // the Date is now just a string{"when":"2025-03-14T10:00:00.000Z","ratio":null,"list":[null,null,null],"tags":{}}
string
Customising conversion
A replacer function controls how values are stringified, and a reviver function transforms values while parsing — for example, to restore dates. Objects can also define a toJSON() method:
const event = { title: "Launch", at: new Date("2025-06-01T09:00:00Z"), secret: "x" };
const json = JSON.stringify(event, (key, value) => (key === "secret" ? undefined : value));
console.log(json);
const restored = JSON.parse(json, (key, value) =>
key === "at" ? new Date(value) : value
);
console.log(restored.at instanceof Date, restored.at.getUTCFullYear());
class Money {
constructor(cents) { this.cents = cents; }
toJSON() { return (this.cents / 100).toFixed(2); }
}
console.log(JSON.stringify({ price: new Money(1999) }));{"title":"Launch","at":"2025-06-01T09:00:00.000Z"}
true 2025
{"price":"19.99"}
Tip:
JSON.parse(JSON.stringify(obj))is an old trick for deep-copying plain data. TodaystructuredClone(obj)is better: it keeps dates, Maps and Sets intact.
Test yourself
Which is valid JSON?
- {name: "Ana"}
- {'name': 'Ana'}
- {"name": "Ana"}
- {"name": "Ana",}
What does JSON.stringify({ a: undefined, b: 1 }) return?
- {"a":undefined,"b":1}
- {"a":null,"b":1}
- {"b":1}
- An error
What does JSON.parse do with invalid input?
- Returns null
- Returns undefined
- Throws a SyntaxError
- Returns the input string