Intermediate · Modules, errors, JSON and dates · topic 28 of 61 · 25 min
JSON: data in and out
Explanation
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.
{
"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 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
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}JSON.parse: text to value
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
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}}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
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.
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); // 1Practice (0/3 done)
Write toJsonPretty(obj) that returns the JSON text of obj indented with 2 spaces.
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" }.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Dates and timesModules, errors, JSON and dates · same module
- Modules: import and exportModules, errors, JSON and dates · same module
- JSON: the language of APIsBackend Development · How the web and backends work
- JSON and working with real dataFrontend Web Development · JavaScript in depth
- Saving data in the browserFrontend Web Development · JavaScript in the browser: DOM and events
- Calling the API with fetchFull-Stack Development · Connecting frontend and backend
Questions people ask about this
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.
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.
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.
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]".
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
- 2 more topics in “Modules, errors, JSON and dates” before its exam: Dates and times, Formatting numbers, money and text with Intl.
- Module 6 exam: Modules, errors, JSON and dates · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Map, Set, iterators, generators and regular expressions. 61 topics left in the course before the final exam.