Find a course

Module 2: JSON: The Language of APIsLesson 4 of 1214 min

Working with JSON in Code

Convert JSON text to live data with JSON.parse and JSON.stringify in JavaScript and json in Python, handle parse errors and reshape nested data.

Step 1 of 15Learn

Text in, objects out: parsing

JSON travels over the network as text. Your program needs real data structures to work with, so the first step after receiving a response is parsing: converting JSON text into the language's native values.

In JavaScript:

const text = '{"city": "Lima", "temp": 18.5, "alerts": []}';
const data = JSON.parse(text);
data.city;            // "Lima"
data.temp + 1;        // 19.5
data.alerts.length;   // 0

In Python, the built-in json module does the same:

import json
data = json.loads('{"city": "Lima", "temp": 18.5, "alerts": []}')
data["city"]          # 'Lima'

The mappings are predictable:

JSONJavaScriptPython
objectobjectdict
arrayarraylist
stringstringstr
numbernumberint or float
true / falsetrue / falseTrue / False
nullnullNone

When you call an API with fetch in JavaScript, await response.json() does the parsing for you. With Python's popular requests library, response.json() does the same. Under the hood, both are the parsing step above.

Step 2 of 15Practice · Match the pairs

Match each JSON value to what Python's json.loads produces.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. {"a": 1}
  2. [1, 2]
  3. null
  4. true
  5. 2.5

Step 3 of 15Compare

What each JSON type becomes after parsing

AspectJSONJavaScript (JSON.parse)Python (json.loads)
Object{ "a": 1 }Objectdict
Array[1, 2]Arraylist
String"hi"stringstr
Number2.5 / 3number (always)float / int
Booleantrue / falsetrue / falseTrue / False
NullnullnullNone

Step 4 of 15Learn

Objects in, text out: serializing

The reverse direction, converting data into JSON text, is called serializing (or encoding). You need it whenever you send data in a request body.

const review = { rating: 5, text: 'Great', draft: undefined };
JSON.stringify(review);                 // '{"rating":5,"text":"Great"}'
JSON.stringify(review, null, 2);        // pretty-printed with 2-space indents

Python:

json.dumps({"rating": 5, "text": "Great"})             # '{"rating": 5, "text": "Great"}'
json.dumps({"rating": 5}, indent=2)                    # pretty-printed

Watch for values JSON can't represent:

  • In JavaScript, properties whose value is undefined or a function are silently dropped, as draft was above. NaN and Infinity become null.
  • A Date object becomes an ISO string, like "2026-03-03T10:15:02.000Z". After parsing, it's still just a string; you must convert it back yourself with new Date(...).
  • Python's json.dumps raises an error for types it doesn't know, such as datetime or set, until you convert them.

A classic bug is forgetting to serialize at all. Sending a JavaScript object as a fetch body without JSON.stringify transmits the useless text [object Object].

Step 5 of 15Practice · What would you do?

What would you do?

A developer sends a new task to an API like this:

fetch('https://api.example.com/tasks', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: { title: 'Write report', due: '2026-04-01' }
});

The server replies 400 Bad Request: invalid JSON. What's wrong?

Step 6 of 15Practice · Diagram

The round trip: serialize, send, parse

Which step did the developer in the scenario skip?

Tap the shape that answers the question, then press Check.

The round trip: serialize, send, parseProcess diagram: Object in your code → Serialize → JSON text on the network → Parse → Object in their code.Object in your codeSerializeJSON text on thenetworkParseObject in their code
Object in your code

{ title: "Write report" } lives in memory.

Serialize

JSON.stringify or json.dumps turns it into text.

JSON text on the network

Only text (bytes) can travel in an HTTP body.

Parse

JSON.parse, response.json() or json.loads on the other side.

Object in their code

A native structure in whatever language the receiver uses.

Step 7 of 15Learn

When parsing fails, and transforming what you get

Parsing can fail. A server under strain might return an HTML error page instead of JSON, or a response might be cut off mid-transfer. JSON.parse then throws a SyntaxError, and Python's json.loads raises json.JSONDecodeError. Code that talks to the network should expect this:

function safeParse(text) {
  try {
    return JSON.parse(text);
  } catch (err) {
    return null;    // or log the error and the first part of the text
  }
}

Once parsed, API data rarely arrives in exactly the shape your screen needs. Typical transformations:

  • Pick a few fields: users.map(u => ({ id: u.id, name: u.name })).
  • Filter records: orders.filter(o => o.status === 'open').
  • Aggregate: items.reduce((sum, i) => sum + i.qty * i.price, 0).
  • Index by ID for fast lookups: build an object or Map from id to record.

Be defensive about missing data. If a field is optional, user.address.city throws when address is null. JavaScript's optional chaining user.address?.city returns undefined instead, and the nullish coalescing operator supplies a default: user.address?.city ?? 'Unknown'. Python code typically uses data.get("address") or {} for the same purpose.

Step 8 of 15Practice · Code challenge

An API returns orders as a JSON string. Write openTotal(jsonText) that parses it and returns the sum of total for orders whose status is "open". If the text is not valid JSON, return 0 instead of throwing.

Runs in a sandbox in your browser.
  • openTotal('[{"id":1,"status":"open","total":20},{"id":2,"status":"paid","total":50},{"id":3,"status":"open","total":5.5}]')
  • openTotal("[]")
  • openTotal("<html>Server error</html>")
  • openTotal('[{"id":9,"status":"paid","total":10}]')

Step 9 of 15Practice · Code challenge

Write cityOf(user) that returns user.address.city, or the string "Unknown" if the user has no address (the field is missing or null) or the address has no city.

Runs in a sandbox in your browser.
  • cityOf({ name: "Ana", address: { city: "Porto" } })
  • cityOf({ name: "Ben", address: null })
  • cityOf({ name: "Cy" })
  • cityOf({ name: "Di", address: { zip: "1000" } })

Step 10 of 15Learn

Validating JSON before you trust it

Valid JSON syntax doesn't mean the data is what you expected. {"price": "free"} parses perfectly, and then price * quantity quietly produces NaN. Data from outside your program, whether an API response or a request your own API receives, should be validated: checked for the right fields, types and ranges before use.

For small cases, simple checks are enough:

if (typeof data.price !== 'number' || data.price < 0) {
  throw new Error('Unexpected price in API response');
}

For larger structures, teams describe the expected shape with a schema and validate automatically. JSON Schema is a widely used standard for this:

{
  "type": "object",
  "required": ["id", "price"],
  "properties": {
    "id": { "type": "string" },
    "price": { "type": "number", "minimum": 0 }
  }
}

Libraries in every major language can check data against such a schema and report exactly which field failed. In Python, libraries such as Pydantic turn the schema into classes; in TypeScript, libraries such as Zod do the same.

Validation matters most on the server side. An API must never trust what clients send, because anyone can craft a request by hand with curl. A client-side form check is a convenience for users; the server-side check is the real protection. Failing loudly on bad data is far better than silently storing garbage that breaks something weeks later.

Step 11 of 15Practice · True or false

If a JSON request body parses without errors, an API can safely store its values without further checks.

Step 12 of 15Practice · Diagram

Layers of checks before you trust incoming JSON

At which layer would {"price": "free"} be rejected?

Tap the shape that answers the question, then press Check.

Layers of checks before you trust incoming JSONFunnel diagram: Raw request text, Valid JSON syntax, Expected shape and types, Sensible values, Safe to use.Raw request textValid JSON syntaxExpected shape and typesSensible valuesSafe to use
Raw request text

Anything at all can arrive.

Valid JSON syntax

It parses without an error.

Expected shape and types

Required fields exist; price is a number, email is a string.

Sensible values

Ranges, lengths, formats: no negative quantities or 10 MB names.

Safe to use

Only now store it or act on it.

Step 13 of 15Note

Step 14 of 15Practice · True or false

After JSON.parse, a field that held "2026-03-03T10:15:02Z" in the JSON text is automatically a Date object in JavaScript.

Step 15 of 15Practice · Choose one

Which line correctly serializes an object to send as a JSON request body in JavaScript?