Access the data (2)
if data: print(data.get('name')) print(data['users'][0]['email'])
### Key Points:
- Use `json.load()` when reading from a **file object**
- Use `json.loads()` when reading from a **string**
- Always specify `encoding='utf-8'` (best practice)
- Use `pathlib.Path` for modern Python code
- Always handle potential `JSONDecodeError` and `FileNotFoundError`
Would you like to see how to also **write** JSON files or work with specific JSON structures (like configurations, lists of objects, etc.)?
````
```json
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "**Reading a JSON file in Python** is very straightforward using the built-in `json` module.\n\n### 1. Basic Method (Recommended)\n\n```python\nimport json\nfrom pathlib import Path\n\n# Method 1: Using pathlib (modern and clean)\ndef read_json_file(file_path):\n with open(file_path, 'r', encoding='utf-8') as file:\n data = json.load(file)\n return data\n\n# Usage\ndata = read_json_file('data.json')\nprint(data)\n```\n\n### 2. Most Common Patterns\n\n```python\nimport json\n\n# Option 1: Using pathlib (Recommended)\ndata = json.loads(Path('data.json').read_text(encoding='utf-8'))\n\n# Option 2: Traditional way\nwith open('data.json', 'r', encoding='utf-8') as f:\n data = json.load(f)\n\n# Option 3: One-liner\ndata = json.load(open('data.json', encoding='utf-8'))\n```\n\n### 3. Complete Example with Error Handling\n\n```python\nimport json\nfrom pathlib import Path\nfrom typing import Any\n\ndef read_json(file_path: str | Path) -> Any:\n \"\"\"Safely read a JSON file with proper error handling.\"\"\"\n try:\n path = Path(file_path)\n with open(path, 'r', encoding='utf-8') as file:\n return json.load(file)\n \n except FileNotFoundError:\n print(f\"Error: File '{file_path}' not found.\")\n return None\n except json.JSONDecodeError as e:\n print(f\"Error: Invalid JSON in '{file_path}': {e}\")\n return None\n except Exception as e:\n print(f\"Unexpected error reading '{file_path}': {e}\")\n return None\n\n\n# Usage examples:\ndata = read_json('config.json')\ndata = read_json(Path('data/settings.json'))\n\n# Access the data\nif data:\n print(data.get('name'))\n print(data['users'][0]['email'])\n```\n\n### Key Points:\n\n- Use `json.load()` when reading from a **file object**\n- Use `json.loads()` when reading from a **string**\n- Always specify `encoding='utf-8'` (best practice)\n- Use `pathlib.Path` for modern Python code\n- Always handle potential `JSONDecodeError` and `FileNotFoundError`\n\nWould you like to see how to also **write** JSON files or work with specific JSON structures (like configurations, lists of objects, etc.)?",
"refusal": null,
"role": "assistant"
}
}
],
"created": 1777675694,
"gatewayMetadata": {
"keySource": "Unified"
},
"id": "90c95869-a6c3-9a03-95d1-32f6a41a14ca",
"model": "grok-4.20-0309-non-reasoning",
"object": "chat.completion",
"system_fingerprint": "fp_bdeb03b7cd",
"usage": {
"completion_tokens": 521,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 0,
"rejected_prediction_tokens": 0
},
"cost_in_usd_ticks": 14165500,
"num_sources_used": 0,
"prompt_tokens": 145,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 64,
"image_tokens": 0,
"text_tokens": 145
},
"total_tokens": 666
}
}
</details>
<details>
<summary>Multi-turn Conversation — Continuing a conversation with context</summary>
const response = await env.AI.run(
'xai/grok-4.20-0309-non-reasoning',
{
max_completion_tokens: 8192,
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)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"model": "xai/grok-4.20-0309-non-reasoning",
"max_completion_tokens": 8192,
"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 excellent stops along (or just off) the main routes from San Francisco to Los Angeles. I’ve grouped them roughly in north-to-south order so you can slot them into your itinerary easily.
### Classic Coastal Route (Highway 1 / Pacific Coast Highway)
This is the most scenic option and the one most people picture when they say “road trip from SF to LA.”
1. **Half Moon Bay** (≈ 30 min south of SF)
- Cute coastal town with beaches, tide pools, and the famous “Pumpkin Festival” in October. Great for a quick coffee or beach walk.
2. **Pescadero & Año Nuevo State Park** (≈ 1 hr from SF)
- Stop at **Duarte’s Tavern** for artichoke soup and pie. Año Nuevo has elephant seals (best Dec–March).
3. **Santa Cruz** (≈ 1.5 hrs from SF)
- Beach Boardwalk, redwood hikes in Henry Cowell Redwoods, or the famous surf at Pleasure Point. Good food scene.
4. **Monterey & Pacific Grove** (≈ 2 hrs from SF)
- Cannery Row, Monterey Bay Aquarium (book ahead), 17-Mile Drive, and the monarch butterfly sanctuary in Pacific Grove (Oct–Feb).
5. **Big Sur** (≈ 3–4 hrs from SF – the heart of the drive)
- **Bixby Bridge** photo stop
- **Point Sur Lighthouse** (tours available)
- **Julia Pfeiffer Burns State Park** – McWay Falls (waterfall onto the beach)
- **Pfeiffer Beach** – purple sand and keyhole rock
- **Nepenthe** or **Big Sur Bakery** for lunch with a view
- **Ventana Big Sur** or **Post Ranch Inn** if you want an upscale overnight.
6. **Cambria / Hearst Castle** (≈ 5–6 hrs from SF)
- Tour the famous Hearst Castle (reservations required).
- Moonstone Beach boardwalk for sunset.
7. **San Luis Obispo (SLO)** (≈ 6.5 hrs from SF)
- Bubblegum Alley, great farm-to-table food, and a lively downtown.
8. **Pismo Beach**
- Classic California beach town with sand dunes you can drive on (ATV tours available).
9. **Solvang** (short detour)
- Danish-themed village with windmills, bakeries, and Æbleskiver pancakes. Fun for 1–2 hours.
10. **Santa Barbara** (≈ 8–9 hrs from SF if you linger)
- “American Riviera.” State Street for shopping, Mission Santa Barbara, beaches, and wine tasting in the Funk Zone.
11. **Malibu** (final stretch before LA)
- Point Dume, El Matador Beach, or a sunset dinner at Malibu Pier.
### Inland / Faster Route Highlights (I-5 corridor)
If you’re short on time but still want stops:
- **Gilroy** – “Garlic Capital of the World” (garlic ice cream if you’re brave).
- **Pacheco Pass** → **San Luis Reservoir** for dramatic views.
- **Harris Ranch** – iconic Central Valley steakhouse stop.
- **Bakersfield** – for Basque food or country-music vibes.
- **Tejon Pass / Magic Mountain** – quick amusement-park option.
### Suggested Itineraries
**Scenic 2-Day Trip (most popular)**
Day 1: SF → Big Sur (overnight in Big Sur or Cambria)
Day 2: Big Sur → Santa Barbara → LA
**3-Day Leisure Trip**
Day 1: SF → Monterey / Carmel (overnight)
Day 2: Monterey → Cambria / Hearst Castle → SLO (overnight)
Day 3: SLO → Santa Barbara → Malibu → LA
Would you like me to:
- Build a day-by-day itinerary with driving times and restaurant recommendations?
- Focus on specific interests (hiking, food, photography, wine, budget, luxury, etc.)?
- Include where to stay or current road conditions / permit info for Big Sur?
Just let me know your preferences (how many days, budget level, must-see activities, etc.) and I’ll tailor it further!
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "Here are some excellent stops along (or just off) the main routes from San Francisco to Los Angeles. I’ve grouped them roughly in north-to-south order so you can slot them into your itinerary easily.\n\n### Classic Coastal Route (Highway 1 / Pacific Coast Highway)\nThis is the most scenic option and the one most people picture when they say “road trip from SF to LA.”\n\n1. **Half Moon Bay** (≈ 30 min south of SF) \n - Cute coastal town with beaches, tide pools, and the famous “Pumpkin Festival” in October. Great for a quick coffee or beach walk.\n\n2. **Pescadero & Año Nuevo State Park** (≈ 1 hr from SF) \n - Stop at **Duarte’s Tavern** for artichoke soup and pie. Año Nuevo has elephant seals (best Dec–March).\n\n3. **Santa Cruz** (≈ 1.5 hrs from SF) \n - Beach Boardwalk, redwood hikes in Henry Cowell Redwoods, or the famous surf at Pleasure Point. Good food scene.\n\n4. **Monterey & Pacific Grove** (≈ 2 hrs from SF) \n - Cannery Row, Monterey Bay Aquarium (book ahead), 17-Mile Drive, and the monarch butterfly sanctuary in Pacific Grove (Oct–Feb).\n\n5. **Big Sur** (≈ 3–4 hrs from SF – the heart of the drive) \n - **Bixby Bridge** photo stop \n - **Point Sur Lighthouse** (tours available) \n - **Julia Pfeiffer Burns State Park** – McWay Falls (waterfall onto the beach) \n - **Pfeiffer Beach** – purple sand and keyhole rock \n - **Nepenthe** or **Big Sur Bakery** for lunch with a view \n - **Ventana Big Sur** or **Post Ranch Inn** if you want an upscale overnight.\n\n6. **Cambria / Hearst Castle** (≈ 5–6 hrs from SF) \n - Tour the famous Hearst Castle (reservations required). \n - Moonstone Beach boardwalk for sunset.\n\n7. **San Luis Obispo (SLO)** (≈ 6.5 hrs from SF) \n - Bubblegum Alley, great farm-to-table food, and a lively downtown.\n\n8. **Pismo Beach** \n - Classic California beach town with sand dunes you can drive on (ATV tours available).\n\n9. **Solvang** (short detour) \n - Danish-themed village with windmills, bakeries, and Æbleskiver pancakes. Fun for 1–2 hours.\n\n10. **Santa Barbara** (≈ 8–9 hrs from SF if you linger) \n - “American Riviera.” State Street for shopping, Mission Santa Barbara, beaches, and wine tasting in the Funk Zone.\n\n11. **Malibu** (final stretch before LA) \n - Point Dume, El Matador Beach, or a sunset dinner at Malibu Pier.\n\n### Inland / Faster Route Highlights (I-5 corridor)\nIf you’re short on time but still want stops:\n\n- **Gilroy** – “Garlic Capital of the World” (garlic ice cream if you’re brave).\n- **Pacheco Pass** → **San Luis Reservoir** for dramatic views.\n- **Harris Ranch** – iconic Central Valley steakhouse stop.\n- **Bakersfield** – for Basque food or country-music vibes.\n- **Tejon Pass / Magic Mountain** – quick amusement-park option.\n\n### Suggested Itineraries\n\n**Scenic 2-Day Trip (most popular)** \nDay 1: SF → Big Sur (overnight in Big Sur or Cambria) \nDay 2: Big Sur → Santa Barbara → LA\n\n**3-Day Leisure Trip** \nDay 1: SF → Monterey / Carmel (overnight) \nDay 2: Monterey → Cambria / Hearst Castle → SLO (overnight) \nDay 3: SLO → Santa Barbara → Malibu → LA\n\nWould you like me to:\n- Build a day-by-day itinerary with driving times and restaurant recommendations?\n- Focus on specific interests (hiking, food, photography, wine, budget, luxury, etc.)?\n- Include where to stay or current road conditions / permit info for Big Sur?\n\nJust let me know your preferences (how many days, budget level, must-see activities, etc.) and I’ll tailor it further!",
"refusal": null,
"role": "assistant"
}
}
],
"created": 1777675700,
"gatewayMetadata": {
"keySource": "Unified"
},
"id": "4eb7a1aa-c8a6-9b80-96e0-b49fe3efbb1d",
"model": "grok-4.20-0309-non-reasoning",
"object": "chat.completion",
"system_fingerprint": "fp_bdeb03b7cd",
"usage": {
"completion_tokens": 915,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 0,
"rejected_prediction_tokens": 0
},
"cost_in_usd_ticks": 24578000,
"num_sources_used": 0,
"prompt_tokens": 190,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 64,
"image_tokens": 0,
"text_tokens": 190
},
"total_tokens": 1105
}
}
</details>
<details>
<summary>Creative Writing — Longer completion for creative output</summary>
const response = await env.AI.run(
'xai/grok-4.20-0309-non-reasoning',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"model": "xai/grok-4.20-0309-non-reasoning",
"max_completion_tokens": 8192,
"messages": [
{
"content": "Write a short story opening about a detective finding an unusual clue.",
"role": "user"
}
]
}'
The rain-slicked alley behind the old theater smelled of rotting velvet and gunpowder. Detective Elias Crowe knelt beside the body, his flashlight beam cutting through the downpour, and paused.
There, clutched in the dead man’s rigid fingers, was a single playing card: the Queen of Hearts. That wasn’t unusual in itself. What stopped Crowe cold was that the card was warm, almost hot, as though it had just come off a printing press. And when he turned it over, the back wasn’t patterned with the usual bicycles or fleurs-de-lis.
It was a tiny, perfectly detailed photograph of the crime scene itself, taken from an angle that should have been impossible—directly above the body, as if the card had been watching the murder happen.
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "The rain-slicked alley behind the old theater smelled of rotting velvet and gunpowder. Detective Elias Crowe knelt beside the body, his flashlight beam cutting through the downpour, and paused.\n\nThere, clutched in the dead man’s rigid fingers, was a single playing card: the Queen of Hearts. That wasn’t unusual in itself. What stopped Crowe cold was that the card was warm, almost hot, as though it had just come off a printing press. And when he turned it over, the back wasn’t patterned with the usual bicycles or fleurs-de-lis.\n\nIt was a tiny, perfectly detailed photograph of the crime scene itself, taken from an angle that should have been impossible—directly above the body, as if the card had been watching the murder happen.",
"refusal": null,
"role": "assistant"
}
}
],
"created": 1777675700,
"gatewayMetadata": {
"keySource": "Unified"
},
"id": "ffb95915-83b7-ac06-34d9-f031b0056ab1",
"model": "grok-4.20-0309-non-reasoning",
"object": "chat.completion",
"system_fingerprint": "fp_bdeb03b7cd",
"usage": {
"completion_tokens": 154,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 0,
"rejected_prediction_tokens": 0
},
"cost_in_usd_ticks": 4865500,
"num_sources_used": 0,
"prompt_tokens": 135,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 64,
"image_tokens": 0,
"text_tokens": 135
},
"total_tokens": 289
}
}
</details>
<details>
<summary>Streaming Response — Enable streaming for real-time output</summary>
const response = await env.AI.run(
'xai/grok-4.20-0309-non-reasoning',
{
messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
stream: true,
stream_options: { include_usage: true },
},
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"model": "xai/grok-4.20-0309-non-reasoning",
"messages": [
{
"content": "Explain the concept of recursion with a simple example.",
"role": "user"
}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
```` Recursion is a programming concept where a function calls itself to solve a smaller version of the same problem.
It's like solving a big problem by repeatedly breaking it down into smaller, identical problems until you reach a simple case that can be solved directly.
Simple Example: Factorial
The factorial of a number n (written as n!) is:
- 5! = 5 × 4 × 3 × 2 × 1 = 120
We can define factorial recursively:
Recursive Definition:
factorial(n) = n × factorial(n-1)← recursive casefactorial(0) = 1← base case (stops the recursion)
Code Example (Python):
```python def factorial(n): # Base case: stop recursion if n == 0 or n == 1: return 1 # Recursive case: call itself with a smaller number else: return n * factorial(n - 1)
