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.
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
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:
[
{
"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.
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.
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())- 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.