Lesson 7 of 20

Data Structures for AI

Working with JSON

3 min read

JSON (JavaScript Object Notation) is the standard format for API communication. Every AI API returns JSON, so mastering it is essential.

JSON Basics

JSON maps directly to Python types:

JSON Python
{} object dict
[] array list
"text" string str
123 number int or float
true/false True/False
null None

Parsing JSON Strings

import json

# JSON string (from API response)
json_string = '{"model": "gpt-4", "temperature": 0.7}'

# Parse to Python dict
data = json.loads(json_string)
print(data["model"])  # "gpt-4"

# Parse JSON with nested structure
api_response = '''
{
    "id": "chatcmpl-123",
    "choices": [
        {"message": {"content": "Hello!"}}
    ]
}
'''
response = json.loads(api_response)
content = response["choices"][0]["message"]["content"]

Converting Python to JSON

import json

# Python dict
message = {
    "role": "user",
    "content": "Hello!"
}

# Convert to JSON string
json_string = json.dumps(message)
# '{"role": "user", "content": "Hello!"}'

# Pretty print with indentation
pretty = json.dumps(message, indent=2)
# {
#   "role": "user",
#   "content": "Hello!"
# }

Reading and Writing JSON Files

import json

# Write to file
config = {"api_key": "hidden", "model": "gpt-4"}
with open("config.json", "w") as f:
    json.dump(config, f, indent=2)

# Read from file
with open("config.json", "r") as f:
    loaded_config = json.load(f)

Common Patterns in AI

import json

# Building API request body
request_body = {
    "model": "gpt-4",
    "messages": [
        {"role": "system", "content": "You are helpful."},
        {"role": "user", "content": "Hello!"}
    ],
    "temperature": 0.7
}

# Convert for HTTP request
json_body = json.dumps(request_body)

# Parsing streaming response chunks
chunk = '{"choices":[{"delta":{"content":"Hi"}}]}'
parsed = json.loads(chunk)
text = parsed["choices"][0]["delta"].get("content", "")

Error Handling

import json

def safe_parse(json_string):
    try:
        return json.loads(json_string)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON: {e}")
        return None

# Usage
result = safe_parse('{"valid": true}')   # Works
result = safe_parse('not json')          # Returns None

Next, we'll learn about type hints to make code clearer. :::

Quiz

Module 2: Data Structures for AI

Take Quiz