Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

JSON: text in the shape of lists and dictionaries

To use a model's answer, not just show it, you ask the model for JSON: text written in almost the same shape as Python lists and dictionaries.

Example
import json

answer = '{"category": "billing", "priority": 4}'
data = json.loads(answer)

print(type(answer))
print(type(data))
print(data["priority"] + 1)

answer is a string that looks like a dictionary. json.loads, load from a string, reads it and builds the real dictionary, so data["priority"] is a number you can add to.

Python values into JSON

Example
result = {"id": 3, "category": "billing", "reply": None, "urgent": True}
print(json.dumps(result))
print(json.dumps(result, indent=2))

json.dumps goes the other way. Look at what changed: JSON writes None as null and True as true, and always uses double quotes. indent=2 spreads it over lines for people to read.

A JSON file

The five tickets the rest of the course uses live in a file:

Exampletickets.json
[
  {
    "id": 1,
    "customer": "Asha",
    "text": "I was charged twice for one order"
  },
  {
    "id": 2,
    "customer": "Ben",
    "text": "My parcel has not arrived"
  },
  {
    "id": 3,
    "customer": "Chen",
    "text": "Can I get a refund for the blue mug?"
  },
  {
    "id": 4,
    "customer": "Dara",
    "text": "How do I change my password?"
  },
  {
    "id": 5,
    "customer": "Eli",
    "text": "The parcel arrived but the box was crushed"
  }
]

Five dictionaries in a list, each with an id, a customer and the text they wrote. Reading the file gives exactly that list back.

Example
with open("tickets.json") as f:
    tickets = json.load(f)

print(len(tickets))
for ticket in tickets:
    print(ticket["id"], ticket["text"])

json.load, without the s, reads from an open file. json.dump writes to one. The file becomes a list of dictionaries, the shape from lesson 9.

Example
counts = {"tickets": len(tickets), "customers": [t["customer"] for t in tickets]}

with open("summary.json", "w") as f:
    json.dump(counts, f, indent=2)

with open("summary.json") as f:
    print(f.read())
Try it yourself
  • Add a sixth ticket to the list after loading, and write the whole list to tickets2.json.
  • Run json.loads("{'category': 'billing'}"), with single quotes inside, and read the error.
  • Print json.dumps([1, "two", None]).

Little by little, you're building something great.