TExcelTAD
Home › JSON › JSON Exercises

JSON Exercises

Time to practise! Each exercise has a starter playground that runs as-is, so you can see where you begin. Change the code, press ▶ Run, and compare your result with the "Expected" description. The solutions are hidden — give each task a real try first.

# Exercise Topics
1 Fix the broken document syntax errors
2 Write a JSON document objects, arrays, data types
3 Read nested values parse, paths
4 Safe parsing try/catch, errors
5 Hide the secrets stringify, replacer
6 Revive the dates parse, reviver, dates
7 Summarise JSON Lines JSON Lines, aggregation
8 Python round trip json module

1. Fix the broken document

The document below contains five mistakes. Fix them until the playground reports Valid JSON: object with 4 keys.

json · try it yourself
{
  'title': "Learning JSON",
  "pages": 0120,
  "published": True,
  "authors": ["Hai", "Yen",],
}
Invalid JSON: Expected property name or '}' in JSON at position 4 (line 2 column 3)
Show solution

The five mistakes: single quotes around title, a leading zero in 0120, True instead of true, and two trailing commas (after "Yen" and after the last pair). Fixing the first three while leaving a trailing comma still fails — every error must go.

json
{
  "title": "Learning JSON",
  "pages": 120,
  "published": true,
  "authors": ["Hai", "Yen"]
}

2. Write a JSON document

Describe a movie as JSON with: title (string), year (number), genres (array of 2 strings), rating (null, not rated yet) and director (an object with name and country).

Expected: Valid JSON: object with 5 keys.

json · try it yourself
{
  "title": "TODO"
}
Valid JSON: object with 1 key
{
  "title": "TODO"
}
Show solution
json
{
  "title": "The River Between",
  "year": 2024,
  "genres": ["drama", "family"],
  "rating": null,
  "director": {"name": "Tran Minh", "country": "Vietnam"}
}

3. Read nested values

Print the customer's city, the number of items, and the SKU of the most expensive item (by unit price).

Expected:

text
Hue
3
LAMP-7
js · try it yourself
const order = JSON.parse(`{
  "customer": {"name": "Thu", "address": {"city": "Hue"}},
  "items": [
    {"sku": "TEA-1", "price": 4.5},
    {"sku": "LAMP-7", "price": 18.0},
    {"sku": "MUG-2", "price": 6.25}
  ]
}`);

// TODO: replace the placeholders
console.log("city?");
console.log("count?");
console.log("sku?");
city?
count?
sku?
Show solution
js
console.log(order.customer.address.city);
console.log(order.items.length);
const top = order.items.reduce((best, it) => (it.price > best.price ? it : best));
console.log(top.sku);

4. Safe parsing

Write tryParse(text, fallback) that returns the parsed value, or fallback if the text is invalid JSON.

Expected:

text
{ a: 1 }
[]
0
js · try it yourself
function tryParse(text, fallback) {
  // TODO: handle invalid JSON
  return JSON.parse(text);
}

console.log(tryParse('{"a": 1}', {}));
try {
  console.log(tryParse("{a: 1}", []));
  console.log(tryParse("", 0));
} catch (err) {
  console.log("Crashed:", err.name);
}
{ a: 1 }
Crashed: SyntaxError
Show solution
js
function tryParse(text, fallback) {
  try {
    return JSON.parse(text);
  } catch {
    return fallback;
  }
}

5. Hide the secrets

Stringify the user so that password and token are removed (wherever they appear, also in nested objects) and the result is indented with 2 spaces.

Expected: the output contains name, email and session.device, but no password or token.

js · try it yourself
const user = {
  name: "Kim",
  email: "kim@example.com",
  password: "s3cret",
  session: { device: "laptop", token: "abc123" },
};

// TODO: add a replacer and indentation
console.log(JSON.stringify(user));
{"name":"Kim","email":"kim@example.com","password":"s3cret","session":{"device":"laptop","token":"abc123"}}
Show solution
js
const HIDDEN = ["password", "token"];
console.log(JSON.stringify(user, (key, value) => (HIDDEN.includes(key) ? undefined : value), 2));

An array replacer such as ["name", "email", "session", "device"] works too, but it is an allow-list: you have to remember every key you want.

6. Revive the dates

Parse the bookings so that every key ending in At becomes a Date. Then print the number of whole hours between checkInAt and checkOutAt.

Expected: true then 46.

js · try it yourself
const text = '{"room": 12, "checkInAt": "2025-07-01T14:00:00Z", "checkOutAt": "2025-07-03T12:00:00Z"}';

const booking = JSON.parse(text);  // TODO: add a reviver

console.log(booking.checkInAt instanceof Date);
console.log("hours?");
false
hours?
Show solution
js
const booking = JSON.parse(text, (key, value) =>
  key.endsWith("At") && typeof value === "string" ? new Date(value) : value
);

console.log(booking.checkInAt instanceof Date);
console.log((booking.checkOutAt - booking.checkInAt) / 3_600_000);

7. Summarise JSON Lines

Each line is one sale. Compute the revenue (qty × price) per region and print the regions alphabetically with 2 decimals. Skip the broken line.

Expected:

text
north: 27.00
south: 31.50
js · try it yourself
const jsonl = `{"region": "north", "qty": 2, "price": 4.5}
{"region": "south", "qty": 3, "price": 10.5}
{"region": "north", "qty": 1 "price": 18}
{"region": "north", "qty": 1, "price": 18}
`;

// TODO: parse each line and sum per region
console.log(jsonl.split("\n").length, "lines");
5 lines
Show solution
js
const totals = {};
for (const line of jsonl.split("\n")) {
  if (!line.trim()) continue;
  let sale;
  try {
    sale = JSON.parse(line);
  } catch {
    continue;
  }
  totals[sale.region] = (totals[sale.region] ?? 0) + sale.qty * sale.price;
}
for (const region of Object.keys(totals).sort()) {
  console.log(`${region}: ${totals[region].toFixed(2)}`);
}

8. Python round trip

Load the JSON, add 10% to every price (rounded to 2 decimals), and print the result as JSON with keys sorted and 2-space indentation.

Expected first lines:

text
[
  {
    "name": "Tea",
    "price": 4.95
  },
python · try it yourself
import json

text = '[{"price": 4.5, "name": "Tea"}, {"price": 20, "name": "Lamp"}]'

# TODO: load, update the prices, dump with indent=2 and sort_keys=True
print(text)
[{"price": 4.5, "name": "Tea"}, {"price": 20, "name": "Lamp"}]
Show solution
python
import json

text = '[{"price": 4.5, "name": "Tea"}, {"price": 20, "name": "Lamp"}]'
products = json.loads(text)
for p in products:
    p["price"] = round(p["price"] * 1.1, 2)
print(json.dumps(products, indent=2, sort_keys=True))

Test yourself

Which change fixes {"tags": ["a", "b",]}?

  1. Use single quotes
  2. Remove the comma after "b"
  3. Quote the brackets
  4. Add a comma after ]

A replacer function returns undefined for a key. What happens?

  1. The key is written as null
  2. The key is omitted
  3. stringify throws
  4. The key is written as "undefined"