Skip to content
Arrays & ObjectsChapter 27 / 47Beginner4 min read

JSON

Learn JavaScript JSON parse and stringify to turn data into text and back into objects, the JSON rules, pretty printing, revivers, and common errors.

On this page

1. What is JSON?

JSON looks like a JavaScript object, but it is actually a string. JavaScript has two built-in methods: JSON.stringify() turns an object into JSON text, and JSON.parse() turns JSON text back into an object.

2. Why does it matter?

You cannot send an object directly over the network or into localStorage, only text goes through. JSON is the common language that the frontend, backend, and database all speak.

Without JSONWith JSON
Every system has its own data formatOne standard format for everyone
Your own code to turn an object into textJSON.stringify in one line
Hard to get data out of textJSON.parse gives an object directly
localStorage holds only stringsStringify the object and save it

3. Where is it used?

AreaWhat JSON does
APIsRequest body and response, res.json()
localStorageSaving a cart or settings as a string
Config filespackage.json, tsconfig.json
DatabasesMongoDB documents, Postgres jsonb columns
LogsStructured logging

4. How does it work?

The journey of data
A JavaScript object
JSON.stringify
A JSON string (network or storage)
JSON.parse
A new JavaScript object

JSON rules

RuleCorrectWrong
Keys in double quotes{"name": "Ali"}{name: "Ali"}
Strings in double quotes"hello"'hello'
No trailing comma[1, 2][1, 2,]
No comments// comment
Allowed valuesstring, number, boolean, null, array, objectundefined, function, Date object

What stringify changes

JavaScript valueIn JSON
undefined / function (inside an object)The property disappears
DateAn ISO string, like "2026-11-01T00:00:00.000Z"
NaN, Infinitynull
Map, Set{} (empty)
BigIntTypeError

5. Code example

Stringify and parse

js
const order = {
  id: 42,
  items: ["pen", "book"],
  paid: false,
  note: undefined,
  createdAt: new Date("2026-11-01"),
};

const text = JSON.stringify(order);
console.log(typeof text);
console.log(text);

console.log(JSON.stringify({ id: 1, tags: ["a"] }, null, 2));

const back = JSON.parse(text);
console.log(back.items[1], typeof back.createdAt);

Safe parse and reviver

js
function safeParse(text, fallback = null) {
  try {
    return JSON.parse(text);
  } catch {
    return fallback;
  }
}

console.log(safeParse("{bad json}", {}));

const saved = '{"name":"Ali","joined":"2026-01-15T00:00:00.000Z"}';
const user = JSON.parse(saved, (key, value) =>
  key === "joined" ? new Date(value) : value
);
console.log(user.joined.getFullYear());

How does the code work?

PartMeaning
typeof text"string", JSON is always text
note: undefinedDisappeared in stringify
createdAtThe Date became an ISO string, and is still a string after parse
JSON.stringify(obj, null, 2)Pretty print with 2 spaces
safeParseA fallback instead of a crash on bad JSON
Reviver functionTurned joined back into a Date during parse, 2026

Interview tip

JSON.parse(JSON.stringify(obj)) is the old deep copy trick, but it breaks Date, undefined, Map, and Set. For a modern deep copy, use structuredClone(obj).

6. Common mistakes

Mistake: Running JSON.parse without try/catch

Why? User input or a broken API response throws a SyntaxError and the whole app crashes.

Better: Parse text that comes from outside inside try/catch and give a fallback.

Mistake: Saving an object directly to localStorage

Why? localStorage.setItem('cart', cart) saves [object Object], and the data is lost.

Better: Use JSON.stringify(cart) when saving and JSON.parse when loading.

Mistake: Treating a Date as a Date object after parse

Why? In JSON a Date is only a string, so methods like getFullYear do not work.

Better: Turn it back into a Date with a reviver function or new Date(value).

Mistake: Parsing an already parsed object again

Why? JSON.parse(object) turns the object into a string and parses that, which throws a SyntaxError.

Better: First check whether the value is a string or an object. fetch's res.json() already parses for you.

7. What to learn before and after

Suggested order
Objects
JSON
Promises
Fetch API
Web Storage

Final quick revision

PointDetail
JSONA text format for data, always a string
JSON.stringifyObject to string
JSON.parseString to object
Pretty printJSON.stringify(obj, null, 2)
Things that disappearundefined, functions
SafetyKeep parse inside try/catch