Practice: JSON API Responses

« Read the chapter

Q1. Parse and print a name

BeginnerCoding

Parse the JSON text {"name": "Asha", "age": 21} and print the name.

Goal: Parse a JSON object.

Q2. Add to a parsed number

BeginnerCoding

Parse '{"price": 120}' and print the price plus 30.

Goal: Use parsed numbers.

Q3. Count list items

BeginnerCoding

Parse '[1, 2, 3, 4]' and print how many items it has.

Goal: Parse a JSON array.

Q4. Sum a field

IntermediateCoding

Parse '[{"qty": 2}, {"qty": 5}, {"qty": 3}]' and print the total of qty.

Goal: Process lists of records.

Q5. Dump with sorted keys

IntermediateCoding

Print the JSON text of {"b": 2, "a": 1} with sorted keys and no indent.

Goal: Write JSON text.

Q6. Default for missing key

IntermediateCoding

Parse '{"name": "Ravi"}' and print the value of country, or Unknown if it is missing.

Goal: Use get with a default.

Q7. Collect names from pages

AdvancedCoding

Two pages are given as JSON strings with a results list. Print one combined list of names.

Goal: Combine paginated data.

Q8. Type of true

BeginnerOutput

What does this print?

Code
import json
print(type(json.loads("true")))

Goal: Know type conversion.

Q9. Null value

BeginnerOutput

What does this print?

Code
import json
print(json.loads("null"))

Goal: Know null maps to None.

Q10. Dumps of a dict

BeginnerOutput

What does this print?

Code
import json
print(json.dumps({"a": True, "b": None}))

Goal: Read dumps output.

Q11. Nested access

IntermediateOutput

What does this print?

Code
import json
d = json.loads('{"u": {"address": {"city": "Pune"}}}')
print(d["u"]["address"]["city"])

Goal: Trace nested access.

Q12. Key type after a round trip

IntermediateOutput

What does this print?

Code
import json
print(json.loads(json.dumps({1: "x"})))

Goal: Know that JSON keys are strings.

Q13. List index of parsed data

IntermediateOutput

What does this print?

Code
import json
rows = json.loads('[{"v": 10}, {"v": 20}]')
print(rows[1]["v"])

Goal: Index into parsed lists.

Q14. Chained get

AdvancedOutput

What does this print?

Code
import json
d = json.loads('{"name": "Z"}')
print(d.get("settings", {}).get("theme", "light"))

Goal: Understand chained get.

Q15. Fix the quotes

BeginnerDebugging

This code fails because the JSON text uses single quotes. Fix it so it prints 5.

Code
import json
data = json.loads("{'n': 5}")
print(data['n'])

Goal: Fix invalid JSON text.

Q16. Parse before use

BeginnerDebugging

This code tries to read a key from a string. Fix it so it prints Leela.

Code
import json
body = '{"name": "Leela"}'
print(body["name"])

Goal: Parse a response body.

Q17. Handle a missing field

IntermediateDebugging

This code raises KeyError for the missing email. Fix it to print no email.

Code
import json
d = json.loads('{"name": "Om"}')
print(d["email"])

Goal: Handle optional fields.

Q18. Why not eval

IntermediateConceptual

Explain in one sentence why json.loads is better than eval for reading an API response.

Goal: Know why JSON parsing is safe.

Q19. Choose load or loads

BeginnerConceptual

You have the text of a response in a variable and also a file called data.json. Which function reads each?

Goal: Choose between load and loads.

Q20. Plan a product list reader

IntermediateApplication

A shop API returns {"count": 2, "items": [{"name": "Pen", "price": 5}, {"name": "Book", "price": 40}]}. Print each name and price on one line as name: price.

Goal: Read an envelope response.