Read JSON file (2)

with open('data.json', 'r') as file: data = json.load(file)

print(data)


## Common Scenarios

### Reading a JSON file with error handling

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError:
    print("Invalid JSON format")

Reading a JSON string (not a file)

import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)  # Note: loads() not load()

print(data['name'])  # Output: Alice

Reading with specific encoding

import json

with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

Key Functions

Function Use Case
json.load(file) Read from a file object
json.loads(string) Parse a JSON string

The result is typically a Python dictionary or list that you can work with normally.


```json
{
  "content": [
    {
      "text": "# Reading JSON Files in Python\n\nPython's built-in `json` module makes it easy to read JSON files.\n\n## Basic Example\n\n```python\nimport json\n\n# Read JSON file\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Common Scenarios\n\n### Reading a JSON file with error handling\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError:\n    print(\"Invalid JSON format\")\n```\n\n### Reading a JSON string (not a file)\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)  # Note: loads() not load()\n\nprint(data['name'])  # Output: Alice\n```\n\n### Reading with specific encoding\n\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n    data = json.load(file)\n```\n\n## Key Functions\n\n| Function | Use Case |\n|----------|----------|\n| `json.load(file)` | Read from a file object |\n| `json.loads(string)` | Parse a JSON string |\n\nThe result is typically a Python dictionary or list that you can work with normally.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_013RFtndBKXc2aNHCwT6Q3cP",
  "model": "claude-opus-4-5-20251101",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 28,
    "output_tokens": 338
  }
}
```

</details>

<details>

<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 1024,
    messages: [
      {
        content: 'I need help planning a road trip from San Francisco to Los Angeles.',
        role: 'user',
      },
      {
        content:
          "I'd be happy to help! The drive is about 380 miles and takes roughly 5-6 hours. Would you like suggestions for scenic routes or interesting stops along the way?",
        role: 'assistant',
      },
      { content: 'Yes, what are some good places to stop?', role: 'user' },
    ],
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "I need help planning a road trip from San Francisco to Los Angeles.",
      "role": "user"
    },
    {
      "content": "I'\''d be happy to help! The drive is about 380 miles and takes roughly 5-6 hours. Would you like suggestions for scenic routes or interesting stops along the way?",
      "role": "assistant"
    },
    {
      "content": "Yes, what are some good places to stop?",
      "role": "user"
    }
  ]
}'
```

```
Here are some great stops depending on your route:

**Coastal Route (Highway 1) - longer but stunning:**
- **Half Moon Bay** - charming coastal town, good breakfast spot
- **Santa Cruz** - boardwalk, beaches, laid-back vibe
- **Monterey/Carmel** - Monterey Bay Aquarium, 17-Mile Drive, beautiful Carmel village
- **Big Sur** - dramatic cliffs, Bixby Bridge, McWay Falls (allow extra time here)
- **San Simeon** - Hearst Castle, elephant seal viewing
- **San Luis Obispo** - cute downtown, Bubblegum Alley
- **Santa Barbara** - Spanish architecture, wine tasting, beaches

**Inland Route (I-5) - fastest:**
- Honestly not much scenic appeal, mostly farmland
- Good for speed, not sightseeing

**Highway 101 (middle ground):**
- Passes through Paso Robles wine country
- Solvang - Danish-themed village

**My suggestion:** If you have time, take Highway 1 down and I-5 back (or vice versa).

How much time do you have for the trip? That'll help me narrow down recommendations.
```

```json
{
  "content": [
    {
      "text": "Here are some great stops depending on your route:\n\n**Coastal Route (Highway 1) - longer but stunning:**\n- **Half Moon Bay** - charming coastal town, good breakfast spot\n- **Santa Cruz** - boardwalk, beaches, laid-back vibe\n- **Monterey/Carmel** - Monterey Bay Aquarium, 17-Mile Drive, beautiful Carmel village\n- **Big Sur** - dramatic cliffs, Bixby Bridge, McWay Falls (allow extra time here)\n- **San Simeon** - Hearst Castle, elephant seal viewing\n- **San Luis Obispo** - cute downtown, Bubblegum Alley\n- **Santa Barbara** - Spanish architecture, wine tasting, beaches\n\n**Inland Route (I-5) - fastest:**\n- Honestly not much scenic appeal, mostly farmland\n- Good for speed, not sightseeing\n\n**Highway 101 (middle ground):**\n- Passes through Paso Robles wine country\n- Solvang - Danish-themed village\n\n**My suggestion:** If you have time, take Highway 1 down and I-5 back (or vice versa).\n\nHow much time do you have for the trip? That'll help me narrow down recommendations.",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_014rC84VWk6CFhWNascdSZwf",
  "model": "claude-opus-4-5-20251101",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 76,
    "output_tokens": 290
  }
}
```

</details>

<details>

<summary>**Creative Writing** — Higher temperature for creative output</summary>

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 512,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    temperature: 0.8,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 512,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "temperature": 0.8
}'
```

```
# The Cartographer's Last Note

Detective Sarah Chen had seen her share of strange crime scenes in fifteen years on the force, but this was the first time she'd found a victim clutching a map to a place that didn't exist.

The body lay in the cramped study, surrounded by towers of yellowed newspapers and the sour smell of old coffee. Standard enough for a recluse. But the paper gripped in Martin Voss's rigid fingers showed hand-drawn streets, elevation markers, and careful notations in faded ink—all depicting a coastal town called Meridian's Rest.

She'd checked. Twice. No such place existed in any database, any historical record, any atlas published in the last two centuries.

Yet the map showed wear patterns from years of folding and unfolding. Coffee stains. A thumbprint in the corner, pressed there so many times it had worn the paper thin.

Martin Voss had spent decades studying a town that had never been built.

Sarah photographed the map, then noticed something that made her breath catch. In the lower corner, nearly invisible against the aged paper, someone had written a date.

Tomorrow's date.

And below it, in handwriting that definitely wasn't the victim's: *You're early. We expected the other detective.*
```

```json
{
  "content": [
    {
      "text": "# The Cartographer's Last Note\n\nDetective Sarah Chen had seen her share of strange crime scenes in fifteen years on the force, but this was the first time she'd found a victim clutching a map to a place that didn't exist.\n\nThe body lay in the cramped study, surrounded by towers of yellowed newspapers and the sour smell of old coffee. Standard enough for a recluse. But the paper gripped in Martin Voss's rigid fingers showed hand-drawn streets, elevation markers, and careful notations in faded ink—all depicting a coastal town called Meridian's Rest.\n\nShe'd checked. Twice. No such place existed in any database, any historical record, any atlas published in the last two centuries.\n\nYet the map showed wear patterns from years of folding and unfolding. Coffee stains. A thumbprint in the corner, pressed there so many times it had worn the paper thin.\n\nMartin Voss had spent decades studying a town that had never been built.\n\nSarah photographed the map, then noticed something that made her breath catch. In the lower corner, nearly invisible against the aged paper, someone had written a date.\n\nTomorrow's date.\n\nAnd below it, in handwriting that definitely wasn't the victim's: *You're early. We expected the other detective.*",
      "type": "text"
    }
  ],
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "id": "msg_01Xn7b7JzMzoHWDigjdGFniq",
  "model": "claude-opus-4-5-20251101",
  "role": "assistant",
  "stop_details": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "type": "message",
  "usage": {
    "input_tokens": 21,
    "output_tokens": 282
  }
}
```

</details>

<details>

<summary>**Streaming Response** — Enable streaming for real-time output</summary>

```ts
const response = await env.AI.run(
  'anthropic/claude-opus-4.5',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
console.log(response)
```

```bash
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-opus-4.5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
```

Understanding Recursion

Recursion is when a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

Key Components

  1. Base case - The condition that stops the recursion
  2. Recursive case - Where the function calls itself with a simpler input

Simple Example: Factorial

factorial(5) = 5 × 4 × 3 × 2 × 1 = 120
def factorial(n):
    # Base case
    if n <= 1:
        return 1
    # Recursive case
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120

How It Works

factorial(5)
  → 5 × factorial(4)
       → 4 × factorial(3)
            → 3 × factorial(2)
                 → 2 × factorial(1)
                      → returns 1  ← base case hit
                 → returns 2 × 1 = 2
            → returns 3 × 2 = 6
       → returns 4 × 6 = 24
  → returns 5 × 24 = 120

Simple Analogy

Think of Russian nesting dolls 🪆 — you keep opening smaller dolls until you reach the smallest one (base case), then you work your way back out.


Remember: Always have a base case, or your function will call itself forever (stack overflow)! ````

[
  {
    "message": {
      "content": [],
      "id": "msg_016ZKcVY6ckQdq7TF4tE5AsJ",
      "model": "claude-opus-4-5-20251101",
      "role": "assistant",
      "stop_details": null,
      "stop_reason": null,
      "stop_sequence": null,
      "type": "message",
      "usage": {
        "cache_creation": {
          "ephemeral_1h_input_tokens": 0,
          "ephemeral_5m_input_tokens": 0
        },
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "inference_geo": "not_available",
        "input_tokens": 19,
        "output_tokens": 1,
        "service_tier": "standard"
      }
    },
    "type": "message_start"
  },
  {
    "content_block": {
      "text": "",
      "type": "text"
    },
    "index": 0,
    "type": "content_block_start"
  },
  "... 15 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]