Practice: JSON API Responses
Q1. Parse and print a name
Parse the JSON text {"name": "Asha", "age": 21} and print the name.
Goal: Parse a JSON object.
Q2. Add to a parsed number
Parse '{"price": 120}' and print the price plus 30.
Goal: Use parsed numbers.
Q3. Count list items
Parse '[1, 2, 3, 4]' and print how many items it has.
Goal: Parse a JSON array.
Q4. Sum a field
Parse '[{"qty": 2}, {"qty": 5}, {"qty": 3}]' and print the total of qty.
Goal: Process lists of records.
Q5. Dump with sorted keys
Print the JSON text of {"b": 2, "a": 1} with sorted keys and no indent.
Goal: Write JSON text.
Q6. Default for missing key
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
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
What does this print?
import json
print(type(json.loads("true")))Goal: Know type conversion.
Q9. Null value
What does this print?
import json
print(json.loads("null"))Goal: Know null maps to None.
Q10. Dumps of a dict
What does this print?
import json
print(json.dumps({"a": True, "b": None}))Goal: Read dumps output.
Q11. Nested access
What does this print?
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
What does this print?
import json
print(json.loads(json.dumps({1: "x"})))Goal: Know that JSON keys are strings.
Q13. List index of parsed data
What does this print?
import json
rows = json.loads('[{"v": 10}, {"v": 20}]')
print(rows[1]["v"])Goal: Index into parsed lists.
Q14. Chained get
What does this print?
import json
d = json.loads('{"name": "Z"}')
print(d.get("settings", {}).get("theme", "light"))Goal: Understand chained get.
Q15. Fix the quotes
This code fails because the JSON text uses single quotes. Fix it so it prints 5.
import json
data = json.loads("{'n': 5}")
print(data['n'])Goal: Fix invalid JSON text.
Q16. Parse before use
This code tries to read a key from a string. Fix it so it prints Leela.
import json
body = '{"name": "Leela"}'
print(body["name"])Goal: Parse a response body.
Q17. Handle a missing field
This code raises KeyError for the missing email. Fix it to print no email.
import json
d = json.loads('{"name": "Om"}')
print(d["email"])Goal: Handle optional fields.
Q18. Why not eval
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
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
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.