AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

JSON and Data Formats: The Language of APIs

📚 APIs & Data Engineering⏱️ 21 min read🎓 Grade 9
✍️ AI Computer Institute Editorial Team Updated: August 2026 CBSE-aligned · Peer-reviewed · 21 min read
Content curated by subject matter experts with IIT/NIT backgrounds. All chapters are fact-checked against official CBSE/NCERT syllabi.

Open the IRCTC app and check the status of a train ticket. You type a PNR number, tap search, and within a second your screen shows the train name, your seat number, and whether your ticket is confirmed or still on the waiting list. That answer did not come from your phone. It travelled from a computer sitting in a railway data centre, possibly hundreds of kilometres away, running code that has nothing to do with the code running on your phone. The server might be written in Java. Your phone's app might be written in Kotlin or JavaScript. These two programs cannot hand each other a live object the way two functions inside the same program can — there is no shared memory, no shared variables, nothing in common except an internet connection. So how does the server tell your phone "seat B4, coach 23, status confirmed" in a way your phone's code can actually use, not just display as a blob of text?

This is the real problem this chapter solves. Two independent programs, possibly written in two different languages, running on two different machines, need to exchange structured information — not just a sentence, but data with parts: a train name, a seat number, a list of passengers, a true/false flag for whether the chart is prepared. They need an agreed-upon written format that both sides can produce and both sides can read back into their own data structures, correctly, every time. That format, for the overwhelming majority of the internet's APIs today, is JSON — JavaScript Object Notation. Despite the name, JSON has nothing to do with actually running JavaScript code; it is purely a way of writing data down as text, and every major programming language can read and write it.

Why a plain sentence or a spreadsheet row isn't enough

Suppose the IRCTC server just sent back a sentence: "Your train is Rajdhani Express, seat B4-23, status confirmed." A human reads this instantly. A program cannot. To extract the seat number, your phone's code would have to search for the word "seat" and then guess where the seat number starts and ends, hoping the server never changes its wording. One tiny change in phrasing — "Seat no. B4-23" instead of "seat B4-23" — and every phone app that reads this sentence breaks. Free-form text is not a data format; it has no fixed structure a program can rely on.

A better idea, and the one used for decades before JSON became common, is CSV — comma-separated values, the format behind a plain spreadsheet export. One PNR could be one row: Rajdhani Express,B4-23,confirmed. This works as long as the data is a single flat row of matching values. But a real PNR is not that simple — one PNR often books multiple passengers, each with their own seat and status, while the train name and date apply once to the whole booking. Force this into CSV and you either repeat the train name on every passenger's row (wasteful and easy to get out of sync), or you invent a second file just for passengers and hope the two files stay linked by PNR number. CSV has no way to say "this one booking contains a list of two passenger records, each with three fields of its own" — it has no concept of nesting, only flat rows and columns. As soon as data has structure inside structure — a booking containing a list, a list containing objects, an object containing another object — CSV runs out of ability to express it cleanly.

JSON: objects and arrays, built from six simple pieces

JSON solves the nesting problem with exactly two container shapes, plus a small set of value types. Once you know these two shapes, you can read or write JSON of any complexity.

An object is a set of key-value pairs, wrapped in curly braces { }. Each key is always a piece of text in double quotes, followed by a colon, followed by a value. Pairs are separated by commas. Think of an object as a labelled form: every blank has a name (the key) and something written in it (the value).

An array is an ordered list of values, wrapped in square brackets [ ], separated by commas. An array doesn't label its items — you find them by position, starting from index 0, exactly like a Python or JavaScript list.

The values inside an object or array can be any of six types: a string ("Rajdhani Express"), a number (23, 4.5), a boolean (true or false, always lowercase, never in quotes), null (meaning "no value", also lowercase and unquoted), or — this is the key idea — another object or another array. Because a value can itself be an object or an array, you can nest as deep as the real data requires: an array of objects, each containing an array, and so on.

Here is the IRCTC PNR response rewritten properly, as actual JSON:

{
  "pnr": "4278391056",
  "train_name": "Rajdhani Express",
  "chart_prepared": true,
  "passengers": [
    { "name": "Aarav Sharma", "seat": "B4-23", "status": "CNF" },
    { "name": "Diya Sharma",  "seat": "B4-24", "status": "CNF" }
  ]
}

Read this the way a computer does: the outer { } is one object with four keys — pnr, train_name, chart_prepared, and passengers. The first three keys hold simple values: two strings and one boolean. The fourth key, passengers, holds an array of two more objects, and each of those inner objects has its own three keys. Nothing about this structure was possible in a single CSV row — the booking-level facts and the per-passenger facts live at different "depths" of the same document, and JSON lets both depths coexist cleanly.

Seeing the structure as a tree

It helps enormously to stop thinking of JSON as "text with brackets" and start seeing it as a tree: the outer object is the root, each key is a labelled branch, and a branch either ends in a leaf value (a string, number, boolean, or null) or grows into another object or array, which itself has more branches. The diagram below is exactly the PNR document above, drawn as that tree.

PNR Response { } object "pnr" "4278391056" "train_name" "Rajdhani Express" "chart_prepared" true "passengers" [ 2 items ] array passengers[0] name: "Aarav Sharma" seat: "B4-23" status: "CNF" passengers[1] name: "Diya Sharma" seat: "B4-24" status: "CNF" Object { } Array [ ] Key : Value leaf

Notice the depths: pnr, train_name, and chart_prepared sit one level below the root — they are leaves, simple values with no further branching. passengers also sits one level below the root, but instead of being a leaf it opens into a second container (the array), which itself opens into two more objects at a third level. When you later write code to read this data, the number of square brackets and dots you type mirrors exactly how many levels deep you must walk down this tree — that correspondence is the single most useful mental model for working with JSON of any size.

Reading JSON the way a program does

A program never "looks" at JSON text the way you do. It runs a parser that reads the text and builds real data structures in memory — Python dictionaries and lists, or JavaScript objects and arrays — from it. In Python, that function is json.loads (load from a string); in JavaScript, it's JSON.parse. Trace through this carefully — every line and its exact output:

import json

pnr_text = '''
{
  "pnr": "4278391056",
  "train_name": "Rajdhani Express",
  "chart_prepared": true,
  "passengers": [
    {"name": "Aarav Sharma", "seat": "B4-23", "status": "CNF"},
    {"name": "Diya Sharma", "seat": "B4-24", "status": "CNF"}
  ]
}
'''

data = json.loads(pnr_text)

print(data["train_name"])
print(data["passengers"][0]["name"])
print(len(data["passengers"]))

Trace it: json.loads reads the text and returns a Python dictionary, so data is now a normal dict with the four keys we saw in the tree. data["train_name"] looks up the key "train_name" in that dict and prints Rajdhani Express. data["passengers"] is a Python list of two dicts; data["passengers"][0] gets the first one (index 0, Aarav's record), and ["name"] pulls his name out of it, printing Aarav Sharma. len(data["passengers"]) counts the items in that list and prints 2. The full output, in order, is:

Rajdhani Express
Aarav Sharma
2

The same document parses identically in JavaScript, because JSON was designed to be language-neutral even though it borrows its syntax from JavaScript object literals:

const pnrData = `{"pnr":"4278391056","chart_prepared":true,
  "passengers":[{"name":"Aarav Sharma","seat":"B4-23"}]}`;

const data = JSON.parse(pnrData);

console.log(data.passengers[0].seat);
console.log(typeof data.chart_prepared);

Here JavaScript lets you use dots instead of square brackets for object keys, so data.passengers[0].seat walks: get the passengers array, take index 0, get its seat field — printing B4-23. typeof data.chart_prepared checks the type of that parsed value and prints boolean, confirming that true in the JSON text really did become a genuine boolean in memory, not the string "true".

The reverse direction — turning your program's own data back into JSON text, ready to send over the internet — uses json.dumps in Python or JSON.stringify in JavaScript:

const marks = { student: "Meera Iyer", subject: "AI", score: 92 };
console.log(JSON.stringify(marks));

This prints exactly {"student":"Meera Iyer","subject":"AI","score":92} — one compact line of text, with no spaces, ready to be sent as the body of a network request. This pair of operations, parsing text into data and serialising data back into text, is what happens on both ends of essentially every API call made from an Indian banking app checking a UPI transaction status, a food-delivery app polling an order's location, or a school portal fetching a student's marks.

The misconception that trips up almost every beginner

Because Python's dictionary printing and JSON look so similar, students very reliably make one specific mistake: assuming that whatever Python prints for a dictionary is JSON. It is not. Watch closely:

person = {'name': "Zoya Khan", 'is_topper': True, 'remarks': None}
print(person)

This prints:

{'name': 'Zoya Khan', 'is_topper': True, 'remarks': None}

That looks close to JSON, but check it against the rules from earlier and three violations appear immediately: it uses single quotes around strings and keys (JSON requires double quotes only), and it uses True and None with capital letters (valid Python keywords, but JSON's boolean and null literals must be the lowercase true, false, and null). If you tried to send this exact text to a server expecting JSON, the server's parser would reject it as malformed. The fix is to never hand-format or eyeball dictionary output as JSON — always run it through json.dumps, which produces the real thing: {"name": "Zoya Khan", "is_topper": true, "remarks": null}. The general lesson: a Python dict and a JSON object look alike on a page, but a Python dict is a live object sitting in your program's memory, while JSON is always text following one exact, strict grammar — readable by any language precisely because it refuses to depend on any single language's conventions.

Spot the error: three broken JSON documents

JSON's strictness is a feature — it means every valid JSON document parses the same way everywhere — but it also means small slips break the whole document. Each snippet below fails to parse. Work out why before reading the explanation.

{
  "name": "Rohan",
  "age": 14,
}

Broken because of the comma left after 14, right before the closing brace. JSON does not allow a trailing comma after the last item in an object or array — every comma must have another value following it.

{
  'city': 'Chennai'
}

Broken because of single quotes. JSON strings and keys must always use double quotes; single quotes are not valid JSON syntax at all, even though many programming languages accept them.

{
  score: 88
}

Broken because the key score has no quotes around it. Every key in a JSON object must be a quoted string — "score", not score — with no exceptions, even for keys that look like simple identifiers.

A second worked example: nested arrays in a weather forecast

Passengers nested inside a booking is one shape of nesting — an array of objects. APIs also commonly nest the other way: an object whose value is itself a deeper structure containing another array. Here is a three-day forecast for Mumbai in the style a real weather API might return it:

{
  "city": "Mumbai",
  "forecast": [
    { "date": "2026-08-14", "condition": "Rain",       "temp_max_c": 29, "temp_min_c": 25 },
    { "date": "2026-08-15", "condition": "Cloudy",     "temp_max_c": 30, "temp_min_c": 26 },
    { "date": "2026-08-16", "condition": "Thunderstorm","temp_max_c": 28, "temp_min_c": 24 }
  ]
}

To find the maximum temperature on the second forecast day, you walk the same two-step path as before: get the array (data["forecast"]), then index into it ([1], since counting starts at 0, so index 1 is the second day), then pull out the field you want (["temp_max_c"]). Written out: data["forecast"][1]["temp_max_c"] evaluates to 30. If you ever feel lost inside a deeply nested JSON document, this is the reliable method — read the path left to right, resolving one bracket at a time, exactly as the tree diagram earlier suggested.

Why JSON won over CSV and XML for APIs

Before JSON became the default, many web APIs used XML, a format that wraps every value in matching opening and closing tags, for example <student><name>Meera Iyer</name></student>. XML can express nesting just as JSON can, and it remains common in specific domains such as some government and banking data-interchange systems. But for the same piece of data, XML needs roughly twice the text, because every tag name is written out twice — once to open, once to close. JSON needed no separate specification effort to become useful to programmers, because its object syntax is literally the object-literal syntax already built into JavaScript, so browsers could turn a JSON string into a working object with almost no extra code; every other major language later added its own JSON library for the same reason. Weighed against CSV, JSON's advantage is nesting and typed values — CSV cannot express "a booking has a list of passengers" without a second file, and every value in a CSV file is just text, so a program reading a CSV must guess whether "true" means the boolean true or literally the three-letter word "true". JSON keeps that information explicit: true written without quotes is unambiguously a boolean, 92 without quotes is unambiguously a number, and "92" with quotes is unambiguously a string, all inside the same document. That is precisely why, when you check a PNR, a UPI transaction, or an exam result online today, the text quietly travelling between the app and the server is, almost always, JSON.

Practice: test what you can retrieve without looking back

  1. Given data = {"school": "DPS Bengaluru", "students": [{"name": "Kabir", "grade": 9}, {"name": "Ishita", "grade": 9}]}, write the exact Python expression that returns the string "Ishita".
  2. Is {"id": 101, "active": True} valid JSON as written? If not, name the exact rule it breaks and rewrite it correctly.
  3. Convert this two-row table into a JSON array of objects, using the column headers as keys: a table with columns Name and Marks, containing the rows Aditi/88 and Rohan/76.
  4. A classmate writes {"scores": [10, 20, 30,]} and says it should parse fine because Python allows a trailing comma in a list literal. Explain why their JSON will still fail to parse.
  5. In the weather forecast example, write the path expression that returns the condition on the first forecast day, and state what it evaluates to.
  6. Explain, in one or two sentences, why CSV cannot cleanly represent the PNR booking with two passengers, while JSON can.

Answers to check yourself: (1) data["students"][1]["name"] — index 1 is Ishita, the second student. (2) No — True must be lowercase true; corrected: {"id": 101, "active": true}. (3) [{"Name": "Aditi", "Marks": 88}, {"Name": "Rohan", "Marks": 76}]. (4) JSON's grammar simply does not permit a trailing comma before a closing bracket, regardless of what the source language that generated the array allowed — JSON has its own fixed grammar independent of any programming language's rules. (5) data["forecast"][0]["condition"], which evaluates to "Rain". (6) CSV only has flat rows and columns, so it cannot express one booking record owning a variable-length list of passenger sub-records without duplicating the shared fields on every row or splitting the data across multiple linked files; JSON expresses this directly by nesting an array of passenger objects inside the booking object.

Summary

JSON exists because two independent programs — a phone app and a server, often written in different languages — need a shared, text-based way to exchange structured data over an API, and neither a plain sentence nor a flat CSV row can represent data that has parts inside parts. JSON supplies exactly two containers, objects ({ }, unordered key-value pairs with double-quoted keys) and arrays ([ ], ordered lists found by index), plus six value types — string, number, boolean, null, object, and array — that can nest inside each other to any depth, which is why it is best understood as a tree rather than as text with punctuation. Parsing (json.loads, JSON.parse) turns that text into real in-memory data structures your code can index into; serialising (json.dumps, JSON.stringify) turns your data back into that same strict text. The single most common beginner error is mistaking a language's own printed representation of a dictionary or object — with single quotes, capitalised True/None, or a trailing comma — for valid JSON; JSON's grammar is fixed and language-independent, which is exactly the property that lets a Java server, a Kotlin phone app, and a Python script all read and write the same document correctly, every time.

Think About It

Think about this: How would you explain json and data formats: the language of apis to a friend who has never seen a computer? What real-world analogy would you use? Imagine you had to build a system using these concepts — what would be your first step? Try this: before moving on, write down three things you learned and one question you still have.

← REST APIs: How Applications Talk to Each OtherAPI Authentication and Security: Keys, Tokens, and OAuth →

Found this useful? Share it!

📱 WhatsApp 🐦 Twitter 💼 LinkedIn