Thuta Learning
JavaScript
AdvancedProgrammingBeginner

JSON Handling

JavaScriptLesson 3930 min

What you'll walk away with

  • Produce readable JSON with JSON.stringify(value, null, 2) and get an object back with JSON.parse
  • Name JSON's six value types and predict what happens to undefined, functions, Dates, NaN and BigInt
  • Handle the SyntaxError from JSON.parse with try/catch
  • Validate the shape and types of parsed data and convert date strings to Date deliberately

Explain it simply

JSON in plain language

JSON (JavaScript Object Notation) is a format for writing data as text. It looks like JavaScript object syntax, but every language, Python, Java, Go and more, can read it, which is why it became the most common format for exchanging data between servers and browsers or between programs and files. In JavaScript, JSON.stringify turns a value into text and JSON.parse turns text back into a value.

It is like shipping flat-pack furniture. stringify takes the wardrobe apart and packs it flat so it can travel; parse assembles it again at the other end. But parts that do not fit in the box, such as functions and undefined, are lost on the way, so the rebuilt wardrobe may not be exactly the original.

Problem → Why → Solution

The problem: the parse succeeds, the data is wrong

To show an order total, you parse the JSON the API returns and multiply price by qty. JSON.parse throws no error, so everything seems fine. But a new backend version now sends price as the string "12.50" and forgot qty entirely. The screen shows Total: NaN, and no error was raised anywhere along the way.

trusting-parse.js
const text = '{"item":"Tea","price":"12.50"}'; // price is a string, qty is missing

const order = JSON.parse(text); // no error: the syntax is valid
const total = order.price * order.qty; // "12.50" * undefined
console.log(`Total: ${total}`); // Total: NaN

What JSON.parse checks, and what it does not

JSON.parse checks only syntax: quotes, commas and brackets. It knows nothing about whether a field exists or whether a value that should be a number is one. Validate the shape and types of all JSON that comes from outside, from an API, a file, localStorage or an upload, right after parsing and before using it.

Core concept: JSON's types and the round trip

JSON has only six value types: object, array, string, number, boolean (true or false) and null. Its syntax is stricter than JavaScript's: keys and strings must use double quotes, and single quotes, trailing commas and comments are not allowed. Parsing {'name': 'Aung'} throws a SyntaxError. There is a single number type with no separate integer, and no way to write NaN, Infinity or undefined at all.

JSON.stringify(value, replacer, space) turns a value into JSON text. Passing 2 as space adds line breaks and indentation for humans; leaving it out gives one compact line suited to sending over the network. The replacer either picks certain keys (an array) or transforms values (a function).

If an object has a toJSON method, stringify uses whatever that method returns instead of the object itself; that is how a Date becomes an ISO string. A replacer is also handy for keeping fields such as passwords out of logs: JSON.stringify(user, ["id", "name"]) writes only those two keys.

JavaScript valueAfter stringify
undefined, function or Symbol in an objectthe key disappears
undefined or a function in an arraybecomes null
NaN, Infinitybecomes null
Datean ISO string (via toJSON)
BigIntthrows a TypeError
circular referencethrows a TypeError

JSON.parse(text, reviver) turns text back into a value and throws a SyntaxError for invalid syntax. Dates come back as plain strings, because JSON has no date type, so you must decide deliberately which fields to turn into Date objects, with a reviver function or after parsing. A round trip through stringify and parse looks like a deep copy, but the table above shows it alters values, so it is not a general-purpose copy; structuredClone is.

JSON as flat-pack shipping
  1. Value → stringify → text
  2. Send or store the text
  3. Text → parse → value (syntax only)
  4. Check shape, types, dates yourself

Functions, undefined and Date objects are changed or lost in the packing.

General pattern

javascript
const text = JSON.stringify(value);              // compact, for sending
const pretty = JSON.stringify(value, null, 2);   // indented, for people

let data;
try {
  data = JSON.parse(text);                       // SyntaxError if malformed
} catch (error) {
  // handle bad input
}
// then: check data's shape and types before using it

Stringify to send or store, parse outside text inside try/catch, and never skip the validation step after parsing.

Worked example: to JSON and back

This example prints a user object as indented JSON, parses it back and reads nested properties, then parses a string shaped like an API response. The code is unchanged from the original; the expected output has been corrected to what Node.js really prints, including the line breaks and blank lines.

json-handling.js
// JavaScript object
const user = {
    name: "Aung Kyaw",
    age: 25,
    skills: ["JavaScript", "Python", "React"],
    address: {
        city: "Yangon",
        country: "Myanmar"
    }
};

// Convert to JSON string
const jsonString = JSON.stringify(user, null, 2);
console.log("JSON String:");
console.log(jsonString);

// Parse JSON back to object
const parsed = JSON.parse(jsonString);
console.log(`\nParsed name: ${parsed.name}`);
console.log(`Skills: ${parsed.skills.join(", ")}`);
console.log(`City: ${parsed.address.city}`);

// Handle nested data
const apiResponse = '{"status":"success","data":{"temp":32,"city":"Yangon"}}';
const weather = JSON.parse(apiResponse);
console.log(`\nTemp in ${weather.data.city}: ${weather.data.temp}°C`);

Code breakdown

  1. Pretty-printconst jsonString = JSON.stringify(user, null, 2);

    The null second argument means no replacer, and 2 indents each level by two spaces. The result is a string, no longer an object.

  2. Parse it backconst parsed = JSON.parse(jsonString);

    parsed is a new object that looks like user but is not the same object; parsed === user is false.

  3. Arrays surviveconsole.log(`Skills: ${parsed.skills.join(", ")}`);

    Arrays stay arrays in JSON, so array methods such as join still work after parsing.

  4. Nested API dataconst weather = JSON.parse(apiResponse);

    API responses are often nested, such as { status, data }. Here data.temp comes back as the number 32, ready for arithmetic, though a real app should still check its type.

You should see
JSON String:
{
  "name": "Aung Kyaw",
  "age": 25,
  "skills": [
    "JavaScript",
    "Python",
    "React"
  ],
  "address": {
    "city": "Yangon",
    "country": "Myanmar"
  }
}

Parsed name: Aung Kyaw
Skills: JavaScript, Python, React
City: Yangon

Temp in Yangon: 32°C

What JSON loses on the way

The event object below mixes values JSON supports with values it does not. The first line shows notes and format vanish while score and the undefined in the array become null. The second line shows the date coming back as a string, and the reviver rebuilds a real Date. The last two lines are the error names for a BigInt and for single-quoted JSON.

json-losses.js
const event = {
  title: "Launch",
  date: new Date(Date.UTC(2025, 0, 15, 9, 30)),
  notes: undefined, // dropped
  score: NaN, // becomes null
  format() { return this.title; }, // dropped
  tags: ["js", undefined], // undefined inside an array becomes null
};
const text = JSON.stringify(event);
console.log(text);

const back = JSON.parse(text);
console.log(typeof back.date, back.date instanceof Date); // string false

const reviver = (key, value) => (key === "date" ? new Date(value) : value);
const revived = JSON.parse(text, reviver);
console.log(revived.date instanceof Date, revived.date.getUTCFullYear()); // true 2025

try {
  JSON.stringify({ big: 10n });
} catch (error) {
  console.log(error.name); // TypeError
}
try {
  JSON.parse("{'name': 'Aung'}");
} catch (error) {
  console.log(error.name); // SyntaxError
}

In real projects

JSON in real projects

JSON is everywhere in web development: REST request and response bodies, config files such as package.json and tsconfig.json, settings saved in localStorage, and structured log lines. The same rules keep returning: guard the parse with try/catch, validate the shape, and convert dates on purpose.

  • localStorage stores only strings, so settings are saved with JSON.stringify and read with JSON.parse. Users can edit the value in DevTools, so a failed parse falls back to the default settings.
  • TypeScript projects validate API responses at runtime with a schema library such as zod, which gives a clear error the moment the shape is wrong, before mistakes like NaN reach the UI.
  • Servers usually send timestamps such as createdAt as ISO 8601 strings like "2025-03-01T08:00:00Z", and the client turns them into Date objects just before formatting them in the user's timezone.

Common mistakes

Common mistakes with JSON

Treating a successful parse as validation

JSON.parse checks syntax only. It does not catch a missing field, a string where a number belongs, or null where an array should be. Check every field you rely on with typeof, Array.isArray, Number.isInteger or a schema library.

Calling JSON.parse without try/catch

A corrupted localStorage value or an HTML error page from the server makes JSON.parse throw a SyntaxError that can break the whole page. Parse all outside text inside try/catch and have a fallback ready.

Expecting a Date to survive the round trip

stringify turns a Date into an ISO string and parse leaves it as a string, so order.createdAt.getFullYear() fails with an 'is not a function' TypeError. Convert it yourself with a reviver or with new Date(order.createdAt).

Best practices

Best practices

  • Keep the three steps for outside JSON, parse, validate and convert, together in one function.
  • Send ids larger than Number.MAX_SAFE_INTEGER as strings, because a JavaScript number would lose precision.
  • Use compact JSON over the network and indented JSON for files or logs that people read.

Mini challenge

Mini challenge: a safe parseOrder

Write parseOrder(text), which accepts order JSON text and never throws. It returns { ok: true, order } with createdAt as a Date, or { ok: false, error }. The five inputs include one valid order, one syntax error, two type errors and one bad date.

  • Wrap JSON.parse in try/catch and report syntax errors with error.name
  • The parsed value must be an object (not null, not an array)
  • id is an integer; items is a non-empty array whose entries have a string name and a positive integer qty
  • createdAt must be a valid date string, returned converted to a Date
parse-order.js
const fail = (error) => ({ ok: false, error });

function parseOrder(text) {
  // TODO: JSON.parse inside try/catch -> fail(`invalid JSON (${error.name})`)
  // TODO: reject anything that is not a plain object
  // TODO: id must be an integer
  // TODO: items must be a non-empty array; check each name and qty
  // TODO: createdAt must parse to a valid Date
  // TODO: return { ok: true, order: { id, items, createdAt } }
}

const inputs = [
  '{"id":7,"items":[{"name":"Tea","qty":2}],"createdAt":"2025-03-01T08:00:00Z"}',
  '{"id":7,"items":[{"name":"Tea","qty":2}],}',
  '{"id":"7","items":[{"name":"Tea","qty":2}],"createdAt":"2025-03-01T08:00:00Z"}',
  '{"id":8,"items":[{"name":"Cake","qty":0}],"createdAt":"2025-03-01T08:00:00Z"}',
  '{"id":9,"items":[{"name":"Juice","qty":1}],"createdAt":"yesterday"}',
];

// TODO: for each input print "ok: order <id>, <n> item(s), year <yyyy>"
// or "rejected: <error>"

Expected: Five lines: ok: order 7, 1 item(s), year 2025; rejected: invalid JSON (SyntaxError); rejected: id must be an integer; rejected: items[0].qty must be a positive integer; rejected: createdAt must be a date string.

Show hint

SyntaxError messages differ between JavaScript engines, so print only error.name. Check a Date with Number.isNaN(date.getTime()).

Show solution
parse-order.js
const fail = (error) => ({ ok: false, error });

function parseOrder(text) {
  let data;
  try {
    data = JSON.parse(text);
  } catch (error) {
    return fail(`invalid JSON (${error.name})`);
  }
  if (typeof data !== "object" || data === null || Array.isArray(data)) {
    return fail("expected an object");
  }
  if (!Number.isInteger(data.id)) return fail("id must be an integer");
  if (!Array.isArray(data.items) || data.items.length === 0) {
    return fail("items must be a non-empty array");
  }
  for (const [i, item] of data.items.entries()) {
    if (typeof item?.name !== "string") return fail(`items[${i}].name must be a string`);
    if (!Number.isInteger(item.qty) || item.qty < 1) {
      return fail(`items[${i}].qty must be a positive integer`);
    }
  }
  const createdAt = new Date(data.createdAt);
  if (typeof data.createdAt !== "string" || Number.isNaN(createdAt.getTime())) {
    return fail("createdAt must be a date string");
  }
  return { ok: true, order: { id: data.id, items: data.items, createdAt } };
}

const inputs = [
  '{"id":7,"items":[{"name":"Tea","qty":2}],"createdAt":"2025-03-01T08:00:00Z"}',
  '{"id":7,"items":[{"name":"Tea","qty":2}],}',
  '{"id":"7","items":[{"name":"Tea","qty":2}],"createdAt":"2025-03-01T08:00:00Z"}',
  '{"id":8,"items":[{"name":"Cake","qty":0}],"createdAt":"2025-03-01T08:00:00Z"}',
  '{"id":9,"items":[{"name":"Juice","qty":1}],"createdAt":"yesterday"}',
];

for (const text of inputs) {
  const result = parseOrder(text);
  if (result.ok) {
    const { id, items, createdAt } = result.order;
    const year = createdAt.getUTCFullYear();
    console.log(`ok: order ${id}, ${items.length} item(s), year ${year}`);
  } else {
    console.log("rejected:", result.error);
  }
}

Quick quiz 1 / 3

What does JSON.stringify({ a: 1, b: undefined, c: [undefined] }) return?

Quick quiz 2 / 3

After const o = JSON.parse(JSON.stringify({ when: new Date() }));, what is typeof o.when?

Quick quiz 3 / 3

Which text does JSON.parse accept without a SyntaxError?

What to remember

  • JSON has six types, object, array, string, number, boolean and null, and allows only double quotes.
  • stringify drops undefined and functions, turns NaN into null and Dates into ISO strings, and throws on BigInt and circular references.
  • JSON.parse checks syntax only and can throw a SyntaxError, so call it inside try/catch.
  • After parsing, validate shape and types, and convert date strings to Date on purpose.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JSON Handling | Thuta Learning