Open and read the JSON file (3)
with open('data.json', 'r', encoding='utf-8') as file: data = json.load(file)
print(data) # data is now a Python dict or list
### Key Points
- **`json.load()`** reads from a file object (as shown above).
- Use the `with` statement to automatically close the file.
- Add `encoding='utf-8'` for safety with non-ASCII characters.
- If you have JSON as a string instead of a file, use `json.loads()`:
```python
import json
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
Handling Errors
import json
try:
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
except FileNotFoundError:
print("File not found.")
except json.JSONDecodeError:
print("Invalid JSON format.")
This is the recommended approach for most use cases. ````
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "To read a JSON file in Python, use the built-in `json` module. Here's the standard way:\n\n```python\nimport json\n\n# Open and read the JSON file\nwith open('data.json', 'r', encoding='utf-8') as file:\n data = json.load(file)\n\nprint(data) # data is now a Python dict or list\n```\n\n### Key Points\n\n- **`json.load()`** reads from a file object (as shown above).\n- Use the `with` statement to automatically close the file.\n- Add `encoding='utf-8'` for safety with non-ASCII characters.\n- If you have JSON as a string instead of a file, use `json.loads()`:\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n```\n\n### Handling Errors\n\n```python\nimport json\n\ntry:\n with open('data.json', 'r', encoding='utf-8') as file:\n data = json.load(file)\nexcept FileNotFoundError:\n print(\"File not found.\")\nexcept json.JSONDecodeError:\n print(\"Invalid JSON format.\")\n```\n\nThis is the recommended approach for most use cases.",
"reasoning_content": "The question is: \"How do I read a JSON file in Python?\"\n",
"refusal": null,
"role": "assistant"
}
}
],
"created": 1778620601,
"gatewayMetadata": {
"keySource": "Unified"
},
"id": "e70ffa7f-a9fa-96d3-ab78-ee0696700ef2",
"model": "grok-4.3",
"object": "chat.completion",
"system_fingerprint": "fp_655c34cb90f68992",
"usage": {
"completion_tokens": 249,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 249,
"rejected_prediction_tokens": 0
},
"cost_in_usd_ticks": 13018500,
"num_sources_used": 0,
"prompt_tokens": 153,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 128,
"image_tokens": 0,
"text_tokens": 153
},
"total_tokens": 651
}
}
</details>
<details>
<summary>Multi-turn Conversation — Continuing a conversation with context</summary>
const response = await env.AI.run(
'xai/grok-4.3',
{
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.3",
"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 the scenic Pacific Coast Highway (Hwy 1) route from San Francisco to Los Angeles, which is far more enjoyable than the faster I-5 inland drive. This path is about 450 miles and takes 8–10 hours of driving time, so plan for 1–2 days with breaks. I've focused on a mix of nature, food, and landmarks, spaced out roughly every 1–2 hours:
### Early Stops (First 2–3 hours from SF)
- **Monterey/Carmel**: Stop for the Monterey Bay Aquarium (world-class marine life exhibits) or a walk along Cannery Row. Nearby, 17-Mile Drive offers stunning coastal views and Pebble Beach golf scenery. Great for lunch—try fresh seafood.
- **Big Sur**: Iconic cliffs, redwoods, and ocean vistas. Pull over at Bixby Creek Bridge for photos or hike in Julia Pfeiffer Burns State Park (McWay Falls is a highlight). Limited services, so gas up beforehand.
### Mid-Trip Stops (Around 4–6 hours in)
- **San Simeon/Hearst Castle**: Tour the opulent Hearst Castle (book ahead) with its pools, gardens, and art collection. Nearby, elephant seal rookeries at Piedras Blancas are free to view from the roadside—amazing wildlife.
- **Morro Bay or Cambria**: Relaxed beach towns. Morro Rock is a volcanic landmark perfect for kayaking or a quick hike. Cambria has cute shops and Moonstone Beach for tidepooling.
### Later Stops (Last 2–3 hours to LA)
- **San Luis Obispo or Pismo Beach**: SLO for a charming downtown with the historic mission and bubblegum alley. Pismo for classic California beach vibes, sand dunes, and clam chowder.
- **Santa Barbara**: "American Riviera" with beautiful beaches, the Spanish-style courthouse for panoramic views, and State Street for shopping/dining. Ideal for an overnight if you're splitting the trip.
### Tips
- **Route note**: Stick to Hwy 1 for scenery (it's slower but worth it); parts can close due to weather/landslides, so check Caltrans updates.
- **Food/essentials**: Pack snacks, as services thin out in Big Sur. Stops like Nepenthe in Big Sur offer cliffside dining.
- **Customization**: If you prefer nature, wine tasting (e.g., near Paso Robles), or family-friendly spots, let me know your interests, group size, or how many days you have—I can refine this or suggest an itinerary with hotels!
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "Here are some excellent stops along the scenic Pacific Coast Highway (Hwy 1) route from San Francisco to Los Angeles, which is far more enjoyable than the faster I-5 inland drive. This path is about 450 miles and takes 8–10 hours of driving time, so plan for 1–2 days with breaks. I've focused on a mix of nature, food, and landmarks, spaced out roughly every 1–2 hours:\n\n### Early Stops (First 2–3 hours from SF)\n- **Monterey/Carmel**: Stop for the Monterey Bay Aquarium (world-class marine life exhibits) or a walk along Cannery Row. Nearby, 17-Mile Drive offers stunning coastal views and Pebble Beach golf scenery. Great for lunch—try fresh seafood.\n- **Big Sur**: Iconic cliffs, redwoods, and ocean vistas. Pull over at Bixby Creek Bridge for photos or hike in Julia Pfeiffer Burns State Park (McWay Falls is a highlight). Limited services, so gas up beforehand.\n\n### Mid-Trip Stops (Around 4–6 hours in)\n- **San Simeon/Hearst Castle**: Tour the opulent Hearst Castle (book ahead) with its pools, gardens, and art collection. Nearby, elephant seal rookeries at Piedras Blancas are free to view from the roadside—amazing wildlife.\n- **Morro Bay or Cambria**: Relaxed beach towns. Morro Rock is a volcanic landmark perfect for kayaking or a quick hike. Cambria has cute shops and Moonstone Beach for tidepooling.\n\n### Later Stops (Last 2–3 hours to LA)\n- **San Luis Obispo or Pismo Beach**: SLO for a charming downtown with the historic mission and bubblegum alley. Pismo for classic California beach vibes, sand dunes, and clam chowder.\n- **Santa Barbara**: \"American Riviera\" with beautiful beaches, the Spanish-style courthouse for panoramic views, and State Street for shopping/dining. Ideal for an overnight if you're splitting the trip.\n\n### Tips\n- **Route note**: Stick to Hwy 1 for scenery (it's slower but worth it); parts can close due to weather/landslides, so check Caltrans updates.\n- **Food/essentials**: Pack snacks, as services thin out in Big Sur. Stops like Nepenthe in Big Sur offer cliffside dining.\n- **Customization**: If you prefer nature, wine tasting (e.g., near Paso Robles), or family-friendly spots, let me know your interests, group size, or how many days you have—I can refine this or suggest an itinerary with hotels!",
"reasoning_content": "The user is asking for good places to stop on a road trip from San Francisco to Los Angeles. This is a continuation from previous messages.\nI think the best stops on a road trip from San Francisco to Los Angeles are along the Pacific Coast Highway (Highway 1) for the most scenic views.",
"refusal": null,
"role": "assistant"
}
}
],
"created": 1778620642,
"gatewayMetadata": {
"keySource": "Unified"
},
"id": "7bf6afe6-09d9-97e0-b3b1-569b9da2b6b5",
"model": "grok-4.3",
"object": "chat.completion",
"system_fingerprint": "fp_655c34cb90f68992",
"usage": {
"completion_tokens": 532,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 458,
"rejected_prediction_tokens": 0
},
"cost_in_usd_ticks": 25881000,
"num_sources_used": 0,
"prompt_tokens": 198,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 128,
"image_tokens": 0,
"text_tokens": 198
},
"total_tokens": 1188
}
}
</details>
<details>
<summary>Creative Writing — Longer completion for creative output</summary>
const response = await env.AI.run(
'xai/grok-4.3',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
