Reading history

JSON in JavaScript: JSON.parse and JSON.stringify

6 min read 2 views

Convert data with JSON.stringify and JSON.parse, pretty-print JSON, handle invalid JSON safely, and use replacers, revivers, toJSON and structuredClone.

JSON (JavaScript Object Notation) is the text format the web uses to exchange data. Servers send JSON to browsers, apps save settings as JSON, and localStorage can only store text, so objects go in as JSON. JavaScript has two built-in functions for it: JSON.stringify turns a value into JSON text, and JSON.parse turns JSON text back into a value. This lesson covers both, including the rules that trip people up and the extra arguments that let you filter and transform data.

In this lesson you will learn

  • Converting values to JSON and back
  • What JSON can and cannot store
  • Pretty-printing with indentation
  • Handling invalid JSON safely
  • Replacers, revivers, toJSON and deep copies

You should know objects and error handling.

stringify and parse

"use strict";
// JSON.stringify turns a value into JSON text
const course = {
  title: "Web Development",
  lessons: 32,
  free: true,
  tags: ["html", "css"],
  teacher: null,
  start: new Date(Date.UTC(2026, 0, 15)),
  helper() { return "hi"; },     // functions are skipped
  extra: undefined,              // undefined is skipped
};
const text = JSON.stringify(course);
console.log(text);
console.log(typeof text, text.length, "characters");

// Pretty printing with indentation
console.log(JSON.stringify({ name: "Rina", marks: [90, 85] }, null, 2));

// JSON.parse turns JSON text back into a value
const back = JSON.parse(text);
console.log(back.title, back.tags[1], typeof back.start);   // dates come back as strings

// Invalid JSON throws a SyntaxError: always catch it for outside data
for (const bad of ["{name: 'Rina'}", '{"a": 1,}', '']) {
  try {
    JSON.parse(bad);
  } catch (e) {
    console.log("Invalid JSON:", JSON.stringify(bad), "->", e.name);
  }
}

Output

{"title":"Web Development","lessons":32,"free":true,"tags":["html","css"],"teacher":null,"start":"2026-01-15T00:00:00.000Z"}
string 124 characters
{
  "name": "Rina",
  "marks": [
    90,
    85
  ]
}
Web Development css string
Invalid JSON: "{name: 'Rina'}" -> SyntaxError
Invalid JSON: "{\"a\": 1,}" -> SyntaxError
Invalid JSON: "" -> SyntaxError
  • JSON.stringify returns a string. JSON supports strings, numbers, booleans, null, arrays and plain objects.
  • Other values are changed or dropped: functions and undefined properties disappear, and a Date becomes an ISO date string.
  • The third argument sets indentation. JSON.stringify(value, null, 2) produces readable output for logs and files.
  • JSON.parse rebuilds objects and arrays. It does not know that a string was once a date, so back.start is just a string.
  • JSON is stricter than JavaScript: keys need double quotes, strings cannot use single quotes, and trailing commas are not allowed. Invalid text, including an empty string, throws a SyntaxError, so wrap JSON.parse in try...catch whenever the text comes from outside your program.

Replacers, Revivers and Deep Copies

"use strict";
// A replacer filters or changes values while stringifying
const user = { name: "Arif", email: "arif@example.com", password: "secret123", age: 21 };
console.log(JSON.stringify(user, ["name", "age"]));          // keep only these keys
console.log(JSON.stringify(user, (key, value) =>
  key === "password" ? undefined : value));                  // drop one key

// toJSON lets an object decide its own JSON form
class Money {
  constructor(taka) { this.taka = taka; }
  toJSON() { return `${this.taka.toFixed(2)} BDT`; }
}
console.log(JSON.stringify({ fee: new Money(1500) }));

// A reviver rebuilds special values while parsing
const json = '{"title":"Exam","date":"2026-03-26T00:00:00.000Z","marks":[1,2]}';
const exam = JSON.parse(json, (key, value) =>
  key === "date" ? new Date(value) : value);
console.log(exam.date instanceof Date, exam.date.getUTCFullYear());

// Deep copy: JSON round trip vs structuredClone
const original = { when: new Date(0), list: [1, [2, 3]], map: new Map([["a", 1]]) };
const viaJson = JSON.parse(JSON.stringify(original));
const viaClone = structuredClone(original);
original.list[1].push(4);
console.log("JSON copy:", typeof viaJson.when, viaJson.list, viaJson.map);
console.log("clone:", viaClone.when instanceof Date, viaClone.list, viaClone.map);

Output

{"name":"Arif","age":21}
{"name":"Arif","email":"arif@example.com","age":21}
{"fee":"1500.00 BDT"}
true 2026
JSON copy: string [ 1, [ 2, 3 ] ] {}
clone: true [ 1, [ 2, 3 ] ] Map(1) { 'a' => 1 }
  • The second argument of stringify is a replacer. An array of keys keeps only those keys; a function sees every key and value and can return undefined to drop one. This is a simple way to keep a password out of logs.
  • If an object has a toJSON() method, stringify uses its result. Here a Money object becomes a formatted string. Date objects work this way too.
  • The second argument of parse is a reviver, called for every key and value. Turning the date string back into a real Date object is its most common use.
  • A JSON round trip, JSON.parse(JSON.stringify(obj)), makes a deep copy, but loses dates, maps and other special types. structuredClone(obj) makes a true deep copy that keeps them.

JavaScript Values in JSON

JavaScript valueResult of JSON.stringify
String, number, boolean, nullKept as they are
Array, plain objectKept, with their contents converted
DateISO string, such as "2026-01-15T00:00:00.000Z"
undefined, function, SymbolDropped from objects; null inside arrays
NaN, Infinitynull
Map, Set{} (contents lost)
BigIntThrows a TypeError

Common Mistakes

  1. Parsing without try...catch, so one bad response crashes the page.
  2. Calling JSON.parse on something that is already an object; it is converted to the string "[object Object]" and fails.
  3. Expecting dates to come back as Date objects without a reviver.
  4. Storing Maps and Sets as JSON directly. Convert them first, for example [...map] or Object.fromEntries(map).

Practice Exercises

Exercise 1. Write safeParse(text, fallback) that returns the parsed value, or fallback if the text is not valid JSON.

Show answer
function safeParse(text, fallback) {
  try {
    return JSON.parse(text);
  } catch {
    return fallback;
  }
}
console.log(safeParse('{"a":1}', {}).a, safeParse("oops", []));   // 1 []

Exercise 2. Save a Set of tags to JSON and read it back as a Set.

Show answer
const tags = new Set(["js", "css"]);
const text = JSON.stringify([...tags]);       // '["js","css"]'
const restored = new Set(JSON.parse(text));

Frequently Asked Questions

Is JSON the same as a JavaScript object?

No. JSON is a text format whose syntax is based on JavaScript object literals. A JavaScript object lives in memory and can hold functions, dates and other types; JSON is a string that can only describe plain data.

Does JSON allow comments?

No. Standard JSON has no comments, and JSON.parse rejects them. Some configuration files use extended formats such as JSONC, but those need special parsers.

Summary

  • JSON.stringify makes text; JSON.parse rebuilds values.
  • JSON stores plain data only; dates become strings and functions are dropped.
  • Always catch errors when parsing outside data.
  • Replacers, revivers and toJSON customise conversion; use structuredClone for deep copies.

Next: JavaScript Timers: setTimeout and setInterval.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *