TalentJR

🟨 JavaScript tutorial for beginners · Class 9 · Lesson 9 of 18 · Free

JSON & Data Formats – Parse and Build Data in JavaScript

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Convert JSON text into JavaScript objects with JSON.parse and back with JSON.stringify
  • Catch errors from broken JSON with try…catch
  • Read JSON from an API and simple CSV data, and show it on a web page

When a weather app asks a server for Pune's temperature, the answer does not travel as a JavaScript object. It travels as plain text in a format called JSON. Every app you use, from cricket scores to train status, sends and receives JSON. In this lesson you learn to read it, write it, and handle it when it is broken.

What is JSON in JavaScript and how is it different from an object?

JSON (JavaScript Object Notation) is a way to write data as TEXT. It looks almost like a JavaScript object, but it is a string.

Text can be sent over the internet, saved in a file, or read by Python, Java and other languages. That is why almost every API uses JSON.

JSON has strict rules: keys in "double quotes", strings in double quotes, no functions, no undefined, no comments, no comma after the last item.

🟨 JavaScript — you can edit this code
Console output
object
string
Asha
undefined
37 characters of text

💡 text.name is undefined because a string has no name key. To use the data, we must first parse it.

How do I convert a JSON string to an object in JavaScript (JSON.parse)?

JSON.parse(text) reads JSON text and builds a real JavaScript value from it: an object, an array, a number, true/false or null.

After parsing you use dots and [ ] as usual. Destructuring from Lesson 7 works too.

Numbers in the JSON stay numbers. Numbers inside quotes stay strings, so check the data carefully.

🎬 How JavaScript thinks — step 1 of 9JavaScript is about to run line 1
▶const text = '{"train":"Rajdhani","coach":"B3","seats":[12,13],"fare":1850}';
2const ticket = JSON.parse(text);
3
4console.log(ticket.train);
5console.log(ticket.seats[1]);
6const { coach, fare } = ticket;
7console.log(`Coach ${coach}, total ₹${fare * 2}`);
8
9const list = JSON.parse("[90, 75, 88]");
10console.log(list.length, Array.isArray(list));
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Rajdhani
13
Coach B3, total ₹3700
3 true

💡 Try it: change "fare":1850 to "fare":"1850" (in quotes). What happens to fare * 2? And to fare + 1?

How do I turn a JavaScript object into JSON (JSON.stringify)?

JSON.stringify(value) does the opposite: it turns an object or array into JSON text, ready to send or save.

Add two more arguments, JSON.stringify(value, null, 2), to get neat text with 2-space indents. Good for reading and debugging.

Some things cannot become JSON. Functions and undefined values are left out silently, and NaN becomes null.

🎬 How JavaScript thinks — step 1 of 8JavaScript is about to run line 1
▶const order = { item: "Masala Dosa", qty: 2, price: 60 };
2const text = JSON.stringify(order);
3console.log(text);
4console.log(typeof text);
5
6console.log(JSON.stringify({ day: "Mon", periods: ["Maths", "Hindi"] }, null, 2));
7
8const odd = { name: "Ravi", nickname: undefined, hello() {}, score: NaN };
9console.log(JSON.stringify(odd));
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
{"item":"Masala Dosa","qty":2,"price":60}
string
{
"day": "Mon",
"periods": [
"Maths",
"Hindi"
]
}
{"name":"Ravi","score":null}

💡 In Class 8 Lesson 13 you saved arrays in localStorage with JSON.stringify and read them back with JSON.parse. Now you know why: localStorage can only store text.

What happens if the JSON is broken, and how do I handle it?

If the text is not valid JSON, JSON.parse throws a SyntaxError and your program stops.

Data from users, files or the internet can be broken. So wrap JSON.parse in try…catch, as you learnt in Lesson 5 (Error Handling).

The function below never crashes. It returns the data, or a safe fallback value if the text is bad.

🟨 JavaScript — you can edit this code
Console output
{ runs: 45 }
Bad JSON: SyntaxError
{}
Bad JSON: SyntaxError
[]

💡 Try it: find what is wrong in the last two strings. (Key without quotes; a comma after the last item.)

How do I get JSON from an API and show it on a web page?

In Lesson 4 you used fetch. The server sends JSON text, and res.json() parses it for you (it is JSON.parse, done for you, with await).

This box uses the TalentJR practice API. Its data is made up, so it is safe to play with.

The code turns the parsed array into list items on the page. Click a name to see that student's full record as pretty JSON.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Got 2 students

💡 Try it: change ?class=9 to ?class=8 and run again.

What other data formats are there, like CSV?

JSON is not the only format. CSV (comma-separated values) is plain text with one row per line and commas between columns. Spreadsheets can save and open it.

CSV has no types, so every value is text. You split it into lines and columns, then convert numbers yourself with Number().

Below we turn a small CSV of marks into an array of objects, and then into JSON. Converting between formats is a very common real task.

🟨 JavaScript — you can edit this code
Console output
["name", "maths", "science"]
[{ name: "Asha", maths: 92, science: 88 }, { name: "Rohan", maths: 67, science: 74 }]
[{"name":"Asha","maths":92,"science":88},{"name":"Rohan","maths":67,"science":74}]

💡 This simple split works only when values have no commas inside them. Real CSV tools handle quotes too.

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

console.log(JSON.stringify({ a: 1, b: undefined, c: "hi" }));

Question 2. What does this print?

const s = JSON.stringify([1, 2]);
console.log(typeof s, s.length);

Question 3. What does this print?

const data = JSON.parse('{"marks": "90"}');
console.log(data.marks + 5);

🧩 Your challenge

A class monitor sends marks as JSON text. Parse it, add an "average" key to each student (rounded with Math.round), and print the result as pretty JSON. Then print who has the highest average. Bad JSON must not crash: wrap the parse in try…catch. Expected end of output: Topper: Zoya (95)

Expected output in the console:
[
  {
    "name": "Asha",
    "marks": [
      92,
      88,
      79
    ],
    "average": 86
  },
  {
    "name": "Zoya",
    "marks": [
      99,
      91,
      94
    ],
    "average": 95
  },
  {
    "name": "Kabir",
    "marks": [
      58,
      62,
      71
    ],
    "average": 64
  }
]
Topper: Zoya (95)
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const text = "{name: 'Asha', cls: 9}";
const student = JSON.parse(text);
console.log(student.name);

SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)

✅ Right

const text = '{"name": "Asha", "cls": 9}';
const student = JSON.parse(text);
console.log(student.name);

In JSON every key and every string needs double quotes. JavaScript-style keys or single quotes are not valid JSON.

❌ Wrong

const student = { name: "Asha", cls: 9 };
const data = JSON.parse(student);
console.log(data.name);

SyntaxError: "[object Object]" is not valid JSON

✅ Right

const student = { name: "Asha", cls: 9 };
console.log(student.name);
const text = JSON.stringify(student);
console.log(JSON.parse(text).name);

JSON.parse needs TEXT. An object is already parsed, so just use it. Parse only strings that came from JSON.stringify, a file or an API.

❌ Wrong

localStorage.setItem("marks", [90, 80]);
const marks = JSON.parse(localStorage.getItem("marks"));
console.log(marks);

SyntaxError: Unexpected non-whitespace character after JSON at position 2 (line 1 column 3)

✅ Right

localStorage.setItem("marks", JSON.stringify([90, 80]));
const marks = JSON.parse(localStorage.getItem("marks"));
console.log(marks);

localStorage turns the array into the text "90,80", which is not JSON. Always JSON.stringify before saving and JSON.parse after reading.

📌 Remember

  • JSON is data written as text; it can travel between servers, files and languages.
  • JSON.parse(text) turns JSON text into a JavaScript value; JSON.stringify(value) turns it back into text.
  • JSON needs double quotes, and has no functions, undefined, comments or trailing commas.
  • Wrap JSON.parse in try…catch when the text might be broken.
  • res.json() parses the JSON an API sends you; CSV is another text format you can split yourself.

Finished the quiz and the challenge?

Questions students ask

What is the difference between JSON and a JavaScript object?

A JavaScript object lives in your program's memory and can hold functions. JSON is text that only describes data. You convert between them with JSON.parse and JSON.stringify.

Why does JSON.parse give 'Unexpected token' or 'Expected property name' errors?

The text is not valid JSON. Common reasons are single quotes, keys without quotes, a comma after the last item, or passing something that is not JSON text at all. Check the text with console.log before parsing.

Can JSON store dates?

Not directly. JSON.stringify turns a Date into a text like "2026-01-26T00:00:00.000Z". After parsing it is just a string, so you make a Date from it again with new Date(text). You will work with dates in Lesson 12.

Is JSON used only with JavaScript?

No. Almost every language, like Python, Java and PHP, can read and write JSON. That is why it is the most common format for APIs.