Skip to content
Laviyx Learn

Try

JavaScript course menu

JSON in JavaScript: JSON.stringify, JSON.parse and Common Pitfalls

Learn JSON (JavaScript Object Notation): its syntax rules, converting objects to JSON with JSON.stringify (with indentation, replacers and toJSON), parsing JSON with JSON.parse safely, what JSON cannot store, and using JSON with APIs and localStorage.

Beginner8 min readUpdated
On this page

JSON (JavaScript Object Notation) is a text format for data. It looks like JavaScript objects and arrays, but it is just a string, which makes it easy to send over a network or save to a file. Nearly every web API sends and receives JSON, in every programming language.

What JSON looks like#

JSON
{
  "name": "Asha Rao",
  "age": 21,
  "isStudent": true,
  "skills": ["HTML", "CSS", "JavaScript"],
  "address": { "city": "Pune", "pin": "411001" },
  "phone": null
}

JSON is stricter than JavaScript:

RuleValid JSONNot valid JSON
Keys in double quotes{"name": "Asha"}{name: "Asha"}
Strings in double quotes"hello"'hello'
No trailing commas[1, 2][1, 2,]
No comments// comment
Valuesstrings, numbers, true, false, null, arrays, objectsundefined, functions, dates, NaN

JSON.stringify: object to text#

JavaScript
const user = { name: "Asha", age: 21, skills: ["HTML", "CSS"] };

const text = JSON.stringify(user);
console.log(text);
console.log(typeof text);
Output
{"name":"Asha","age":21,"skills":["HTML","CSS"]}
string

Pretty printing#

The third argument adds indentation, which makes JSON readable for people and logs:

JavaScript
const user = { name: "Asha", skills: ["HTML", "CSS"] };
console.log(JSON.stringify(user, null, 2));
Output
{
  "name": "Asha",
  "skills": [
    "HTML",
    "CSS"
  ]
}

Choosing what to include#

The second argument, the replacer, can be an array of keys to keep, or a function:

JavaScript
const account = { username: "asha", password: "secret123", plan: "pro" };

console.log(JSON.stringify(account, ["username", "plan"]));
console.log(JSON.stringify(account, (key, value) => (key === "password" ? undefined : value)));
Output
{"username":"asha","plan":"pro"}
{"username":"asha","plan":"pro"}

JSON.parse: text to object#

JavaScript
const text = '{"product":"Pen","price":20,"tags":["blue","gel"]}';

const data = JSON.parse(text);
console.log(data.product, data.price);
console.log(data.tags[1]);
Output
Pen 20
gel

Parse safely#

Invalid JSON throws a SyntaxError. Data from outside your program (an API, a file, localStorage) can be broken, so wrap parsing in try...catch:

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

console.log(safeParse('{"ok": true}', {}));
console.log(safeParse("{name: 'Asha'}", {}));
console.log(safeParse("", []));
Output
{ ok: true }
{}
[]

What JSON loses#

JSON only has strings, numbers, booleans, null, arrays and objects. Other values change or disappear:

JavaScript
const event = {
  title: "Workshop",
  date: new Date("2026-11-14T10:00:00Z"),
  notes: undefined,
  onClick() {},
  attendees: new Set(["Asha"]),
  score: NaN,
};

console.log(JSON.stringify(event));
Output
{"title":"Workshop","date":"2026-11-14T10:00:00.000Z","attendees":{},"score":null}
  • Date becomes an ISO string; JSON.parse gives you back a string, not a Date.
  • undefined values and functions are dropped.
  • Set and Map become {}. Convert them first: [...set] or Object.fromEntries(map).
  • NaN and Infinity become null.

Restoring dates with a reviver#

JSON.parse takes an optional reviver function to convert values back:

JavaScript
const text = '{"title":"Workshop","date":"2026-11-14T10:00:00.000Z"}';
const event = JSON.parse(text, (key, value) => (key === "date" ? new Date(value) : value));

console.log(event.date instanceof Date);
console.log(event.date.getUTCFullYear());
Output
true
2026

Deep copies#

JSON.parse(JSON.stringify(obj)) was the classic way to deep-copy data, but it loses dates, undefined, Maps and so on. Use structuredClone(obj) instead.

Where you will use JSON#

  • APIs: fetch responses are usually JSON, read with response.json() (Fetching Data).
  • Saving in the browser: localStorage only stores strings, so objects are saved with JSON.stringify (localStorage).
  • Configuration files: package.json, tsconfig.json and many others.

Practice#

Practice exercise

Convert this array of tasks to pretty-printed JSON with 2-space indentation, but leave out the internalId field. Then parse the JSON back and print how many tasks are done.

JavaScript
const tasks = [
  { internalId: "x1", title: "Learn JSON", done: true },
  { internalId: "x2", title: "Practise fetch", done: false },
];
Show solution
JavaScript
const tasks = [
  { internalId: "x1", title: "Learn JSON", done: true },
  { internalId: "x2", title: "Practise fetch", done: false },
];

const json = JSON.stringify(tasks, ["title", "done"], 2);
console.log(json);

const parsed = JSON.parse(json);
console.log(parsed.filter((t) => t.done).length);
Output
[
  {
    "title": "Learn JSON",
    "done": true
  },
  {
    "title": "Practise fetch",
    "done": false
  }
]
1

Key takeaway#

Finished this lesson?