JSON (JavaScript Object Notation) is the most common way for programs to swap data. Web APIs, AI APIs, configuration files and smart home devices all use it. It's easy for people to read and easy for programs to process, and there are only a few rules to learn.
What JSON looks like
{
"name": "Raspberry Pi Pico 2 W",
"price": 7.0,
"in_stock": true,
"pins": ["GP0", "GP1", "GP2"],
"specs": {"ram_kb": 520, "wifi": true},
"notes": null
}
The rules
- Objects are wrapped in
{ }and hold"key": valuepairs, separated by commas. - Arrays (lists) are wrapped in
[ ]. - Keys must be strings in double quotes.
- Values can be a string (in double quotes), a number,
true,false,null, an object or an array. - Objects and arrays can be nested inside each other as deeply as you need.
Common mistakes
JSON is strict, and these all make it invalid:
- Single quotes:
{'name': 'Pico'}must be{"name": "Pico"}. - A trailing comma after the last item:
[1, 2, 3,]. - Comments. JSON doesn't allow
//or#comments. - Python's
True,FalseandNoneinstead of JSON'strue,falseandnull.
JSON in Python
Python's built-in json module converts between JSON text and Python dictionaries and lists:
import json
text = '{"name": "Pico 2 W", "price": 7.0, "in_stock": true, "pins": ["GP0", "GP1"]}'
board = json.loads(text) # JSON text -> Python dict
print(board["name"], board["pins"][1], board["in_stock"])
# Pico 2 W GP1 True
board["price"] = 6.5
print(json.dumps(board)) # Python dict -> JSON text
# {"name": "Pico 2 W", "price": 6.5, "in_stock": true, "pins": ["GP0", "GP1"]}
# Save to and load from a file
with open("board.json", "w") as f:
json.dump(board, f, indent=2)
with open("board.json") as f:
print(json.load(f)["price"])
# 6.5
try:
json.loads("{'name': 'Pico'}")
except json.JSONDecodeError as e:
print("Invalid JSON:", e.msg)
# Invalid JSON: Expecting property name enclosed in double quotes
Notice that JSON's true became Python's True, and back again.
Getting JSON from AI models
JSON is how you turn an AI model's answer into data your program can use, such as fields pulled from an email or a list of tags. Two approaches:
- Ask for it clearly in the prompt, with an example: "Reply with only a JSON object with the keys name, email and topic." This usually works, but always wrap
json.loadsin atryblock in case the reply isn't valid. - Use structured outputs where the API offers them. You give a schema, a description of the exact shape you want, and the API guarantees the reply matches it. Anthropic, OpenAI and Google all offer this.
Here's structured output with Anthropic's Python library, which uses a Pydantic class as the schema:
from pydantic import BaseModel
import anthropic
class Enquiry(BaseModel):
name: str
email: str
topic: str
client = anthropic.Anthropic()
response = client.messages.parse(
model="claude-haiku-5-5",
max_tokens=1024,
messages=[{"role": "user", "content":
"Extract the details: Hi, Sam here (sam@example.com). My soldering iron won't heat up."}],
output_format=Enquiry,
)
print(response.parsed_output)
New to AI APIs? Start with your first AI API program, and see how to write better prompts.
Going deeper
Describing structure with JSON Schema
JSON Schema is a standard way to describe what valid JSON looks like: which keys are required, their types and allowed values. APIs use it to document requests, and AI structured outputs use it to constrain replies. In Python, Pydantic models generate and enforce schemas:
from pydantic import BaseModel, Field, ValidationError
class Part(BaseModel):
name: str
price: float = Field(ge=0)
stock: int = 0
print(Part.model_validate_json('{"name": "LED", "price": 0.05}'))
try:
Part.model_validate_json('{"name": "LED", "price": -1}')
except ValidationError as e:
print(e.error_count(), "error:", e.errors()[0]["msg"])
print(sorted(Part.model_json_schema()["properties"]))
name='LED' price=0.05 stock=0
1 error: Input should be greater than or equal to 0
['name', 'price', 'stock']
JSON Lines for big data
A single huge JSON array must usually be loaded into memory all at once. JSON Lines (.jsonl) puts one JSON object per line, so files can be streamed, appended to and processed line by line. Batch AI APIs and many data tools use it.
import json
rows = [{"id": 1, "text": "hello"}, {"id": 2, "text": "world"}]
with open("data.jsonl", "w") as f:
for row in rows:
f.write(json.dumps(row) + "\n")
with open("data.jsonl") as f:
for line in f:
print(json.loads(line)["text"])
Numbers and precision
JSON itself doesn't limit number size, but JavaScript stores numbers as 64-bit floating point, which represents integers exactly only up to 253 (9,007,199,254,740,992). Larger IDs can silently change when read in a browser. That's why many APIs send big IDs as strings. Python's json module handles large integers exactly. Floating-point values like 0.1 can't be stored exactly in binary, so use integers (such as pence) for money.
Text encoding
JSON text should be UTF-8. Python's json.dumps escapes non-ASCII characters like "£" as £ by default. Pass ensure_ascii=False to keep them readable, and open files with encoding="utf-8".
Security
Always parse JSON with a real parser, never with eval(), which would run any code hidden in the data. Validate the structure of JSON from outside sources, including AI models, before trusting it.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.