Skip to content

Intermediate · Modules, errors, JSON and dates · topic 28 of 61 · 25 min

JSON: data in and out

Explanation

JSON (JavaScript Object Notation) is a text format for data that every language understands, used by almost every web API. JSON.stringify turns a value into JSON text and JSON.parse turns text back into a value. JSON is stricter than JavaScript: double-quoted keys and strings, no functions, no undefined, no comments and no trailing commas.

Why JSON?

Programs need to send data to each other: a phone app to a server, a server to a database, a config file to a program. They may be written in different languages. JSON is a plain-text format that looks like JavaScript objects and arrays, and every major language can read and write it. When IRCTC's app asks for your PNR status, the answer most likely comes back as JSON.

json
{
  "pnr": "4521367890",
  "train": { "number": "12951", "name": "Mumbai Rajdhani" },
  "passengers": [
    { "name": "Asha", "status": "CNF", "berth": "B2-34" },
    { "name": "Ravi", "status": "WL", "position": 4 }
  ],
  "chartPrepared": false,
  "remarks": null
}
JSON allows objects, arrays, strings, numbers, true, false and null.

JSON rules (stricter than JavaScript)

  • Keys must be in double quotes: {"name": "Asha"}, not {name: "Asha"}.
  • Strings use double quotes only, never single quotes.
  • No trailing comma after the last item.
  • No comments, no functions, no undefined, no NaN or Infinity, no Dates (use strings).

JSON.stringify: value to text

javascript
const order = { id: 7, items: ['tea', 'biscuit'], paid: true, note: undefined, at: new Date(0) };
console.log(JSON.stringify(order));
// {"id":7,"items":["tea","biscuit"],"paid":true,"at":"1970-01-01T00:00:00.000Z"}
console.log(JSON.stringify(order, null, 2));     // pretty-printed with 2-space indent
console.log(JSON.stringify(order, ['id', 'paid'])); // only these keys: {"id":7,"paid":true}
Careful: stringify silently changes data: properties with undefined or function values disappear, NaN and Infinity become null, Dates become ISO strings, and Map and Set become {}. After a round trip through JSON, a Date is a string, so call new Date(str) when you need a Date again.

JSON.parse: text to value

javascript
const text = '{"amount": 1499, "currency": "INR"}';
const payment = JSON.parse(text);
console.log(payment.amount + 1); // 1500

try {
  JSON.parse("{'amount': 1}");   // single quotes are not JSON
} catch (e) {
  console.log(e.name);           // SyntaxError
}

Text from outside your program (a file, a network response, localStorage) can be broken or not JSON at all. Always wrap JSON.parse of outside data in try/catch, and check the shape of the result before trusting it.

Reviver and toJSON

javascript
const data = '{"name":"Asha","joined":"2025-07-01T00:00:00.000Z"}';
const user = JSON.parse(data, (key, value) =>
  key === 'joined' ? new Date(value) : value
);
console.log(user.joined instanceof Date); // true

class Money {
  constructor(paise) { this.paise = paise; }
  toJSON() { return { rupees: this.paise / 100 }; }  // controls stringify
}
console.log(JSON.stringify({ price: new Money(9950) })); // {"price":{"rupees":99.5}}
Think of it like this: JSON is like a courier parcel form that every courier company in the world accepts. Whatever is inside your house (functions, Dates, Maps), you must first write it out on the standard form, and the receiver rebuilds it at their end.
Tip: When debugging, console.log(JSON.stringify(obj, null, 2)) shows the full nested structure at a moment in time, which is clearer than an expandable console object that may change later.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

JSON: data in and out · 1/6

JSON

In this lesson you will move data in and out of your programs as JSON.

Prefer a video by a teacher? Find free videos on “javascript JSON stringify parse explained” on YouTube ↗

In real life: Saving a cart in the browser

A shopping site keeps the cart when you close the tab by saving it in localStorage, which can only store strings. It stringifies the cart on every change and parses it when the page opens, falling back to an empty cart if the saved text is broken.

javascript
const saved = '[{"sku":"TSHIRT-M","qty":2}]'; // what localStorage.getItem('cart') returned
let cart;
try {
  cart = JSON.parse(saved) ?? [];
} catch {
  cart = [];
}
console.log(cart.length); // 1

Practice (0/3 done)

Task 1 · Code · Javascript

Write toJsonPretty(obj) that returns the JSON text of obj indented with 2 spaces.

Task 2 · Code · Javascript

Write parseOrder(text). It must return the parsed order object when the text is valid JSON AND has a numeric amount property; otherwise return { error: "Invalid order" }.

Task 3 · Code · Javascript

Write reviveDates(text) that parses JSON and turns every string value whose key ends with "At" (like createdAt, paidAt) into a Date object, using a reviver.

Quick quiz

Question 1

1.Which is valid JSON?

Question 2

2.What is JSON.stringify({ a: undefined, b: 1 })?

Question 3

3.What type is JSON.parse(JSON.stringify(new Date())) ?

Question 4

4.JSON.parse("{'x': 1}") throws which error?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which is valid JSON?

Answer: {"a": 1}

JSON needs double-quoted keys and no trailing comma.

What is JSON.stringify({ a: undefined, b: 1 })?

Answer: {"b":1}

Properties with undefined values are left out.

What type is JSON.parse(JSON.stringify(new Date())) ?

Answer: string

Dates are stringified to ISO text and parsed back as plain strings.

JSON.parse("{'x': 1}") throws which error?

Answer: SyntaxError

Single quotes are not valid JSON, so parsing fails with SyntaxError.

What happens when JSON.parse gets broken text?Related

Answer: It throws a SyntaxError

JSON.parse throws on bad input, so wrap it in try and catch.

From JSON: the language of APIs

After const back = JSON.parse(JSON.stringify({ when: new Date() })), what is back.when?Related

Answer: A string like "2026-10-19T08:30:00.000Z"

JSON has no date type. stringify writes the date as an ISO string, and parse leaves it as a string. Use new Date(back.when) to get a Date again.

From JSON and working with real data

What does localStorage.getItem('pincode') return when nothing was saved under that key?Related

Answer: null

getItem returns null for a missing key, so always plan a default value.

From Saving data in the browser

What does body: JSON.stringify(note) do?Related

Answer: Turns the object into JSON text, because a request body must be a string

fetch sends text. Passing a plain object would send "[object Object]".

From Calling the API with fetch

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Modules, errors, JSON and dates” before its exam: Dates and times, Formatting numbers, money and text with Intl.
  2. Module 6 exam: Modules, errors, JSON and dates · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Map, Set, iterators, generators and regular expressions. 61 topics left in the course before the final exam.

← Previous: Error handling: try, catch, finally and throw