data.json: {"users": [{"name": "Ada", "roles": ["admin"]}]}

data["users"][0]["name"] # "Ada" data["users"][0]["roles"][0] # "admin"


Use `.get()` for keys that might be missing:

```python
email = data["users"][0].get("email", "unknown")

Handling errors properly

Real-world files are messy. Catch the two things that actually go wrong:

import json
from pathlib import Path

def read_json(path):
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"No such file: {path}")
    except json.JSONDecodeError as e:
        print(f"Invalid JSON in {path} at line {e.lineno}, column {e.colno}: {e.msg}")
    return None

data = read_json("data.json")

JSONDecodeError is a subclass of ValueError, and it carries lineno, colno, and pos — genuinely useful for pinpointing a bad comma.

Using pathlib (slightly tidier)

import json
from pathlib import Path

data = json.loads(Path("data.json").read_text(encoding="utf-8"))

Common gotchas

Always specify encoding="utf-8". Without it, Python uses the platform default, which on some Windows setups is cp1252 and will blow up on non-ASCII characters. JSON is UTF-8 by spec.

JSON Lines (.jsonl) is a different format. One JSON object per line — json.load() will fail. Parse line by line:

with open("data.jsonl", encoding="utf-8") as f:
    records = [json.loads(line) for line in f if line.strip()]

Trailing commas and comments aren't valid JSON. {"a": 1,} or // comment will raise JSONDecodeError. If you're stuck with such files, use the json5 or commentjson package.

Huge files: json.load() builds the whole structure in memory. For files that don't fit, use a streaming parser like ijson:

import ijson

with open("huge.json", "rb") as f:
    for record in ijson.items(f, "users.item"):
        process(record)

Writing it back out

For completeness:

with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

indent=2 makes it human-readable; ensure_ascii=False keeps non-ASCII characters as-is instead of escaping them to \uXXXX. ````

{
  "id": "msg_011CdMcXtLbe6orhyjErTMK4",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAISlgMKhwEIEBgCKkAMw2x29hUCKlXqNB76pH+D/yqNHzKCZSWl13/1q5MvcRHqGBsMYVt5OPNJRBpoK96H4yBdLeYFynRrC3brOl8VMg1jbGF1ZGUtb3B1cy01OAFCCHRoaW5raW5nWiQ5ODY2MTIzNC03NmUwLTRlMGQtYTgyMS1iZThmOGMzNDc0ZDYSDPHl470mvTSS/VVloBoMjuO0rbloh1ffzl7/IjCQVDk88te+JO4ShyaKbxvx7tByViz6N6zO3AnWMoRShuVZmByIC9M123krmAR3d0squwH0oba6v809aPGBRis6zXZjjkxj9xUPeK9bIiAs2F4LqShktrO0enUaJGxlcocxt2tmwdkC5SF7XOy5lKpcBDf6XvOTeaV0bYyxgAQ6L2FkiOU9NtnSGiZZ0VmKz2v8RZ9nVisaD6kA15+UOqX8SO5ZYny+Ttrgue6Cx5DJ7MfBcRcE6SsSsuyLnrRFY1S7XNsCcd0lY1rv1CzkYOnItoxD6fDWab8uxQGGXWBhUnSy4XxtZ0+TR/2fRTuXGAE="
    },
    {
      "type": "text",
      "text": "# Reading JSON Files in Python\n\nPython's built-in `json` module handles this. The key function is `json.load()`.\n\n## The basic pattern\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)\n\nprint(data)\n```\n\nThat's it. `json.load()` reads from a file object; the `with` statement ensures the file gets closed even if something goes wrong.\n\n## `load()` vs `loads()`\n\nThis trips people up constantly:\n\n| Function | Input | Use when |\n|---|---|---|\n| `json.load(f)` | file object | reading from a file |\n| `json.loads(s)` | string (or bytes) | you already have JSON text |\n\n```python\n# From a string\ntext = '{\"name\": \"Ada\", \"age\": 36}'\ndata = json.loads(text)\n\n# Equivalent to the file version\nwith open(\"data.json\", encoding=\"utf-8\") as f:\n    data = json.loads(f.read())   # works, but load(f) is cleaner\n```\n\n## What you get back\n\nJSON types map to Python types like this:\n\n```\nobject  -> dict\narray   -> list\nstring  -> str\nnumber  -> int / float\ntrue    -> True\nfalse   -> False\nnull    -> None\n```\n\nSo access it like any nested dict/list:\n\n```python\n# data.json: {\"users\": [{\"name\": \"Ada\", \"roles\": [\"admin\"]}]}\ndata[\"users\"][0][\"name\"]        # \"Ada\"\ndata[\"users\"][0][\"roles\"][0]    # \"admin\"\n```\n\nUse `.get()` for keys that might be missing:\n\n```python\nemail = data[\"users\"][0].get(\"email\", \"unknown\")\n```\n\n## Handling errors properly\n\nReal-world files are messy. Catch the two things that actually go wrong:\n\n```python\nimport json\nfrom pathlib import Path\n\ndef read_json(path):\n    try:\n        with open(path, \"r\", encoding=\"utf-8\") as f:\n            return json.load(f)\n    except FileNotFoundError:\n        print(f\"No such file: {path}\")\n    except json.JSONDecodeError as e:\n        print(f\"Invalid JSON in {path} at line {e.lineno}, column {e.colno}: {e.msg}\")\n    return None\n\ndata = read_json(\"data.json\")\n```\n\n`JSONDecodeError` is a subclass of `ValueError`, and it carries `lineno`, `colno`, and `pos` — genuinely useful for pinpointing a bad comma.\n\n## Using `pathlib` (slightly tidier)\n\n```python\nimport json\nfrom pathlib import Path\n\ndata = json.loads(Path(\"data.json\").read_text(encoding=\"utf-8\"))\n```\n\n## Common gotchas\n\n**Always specify `encoding=\"utf-8\"`.** Without it, Python uses the platform default, which on some Windows setups is cp1252 and will blow up on non-ASCII characters. JSON is UTF-8 by spec.\n\n**JSON Lines (`.jsonl`) is a different format.** One JSON object per line — `json.load()` will fail. Parse line by line:\n\n```python\nwith open(\"data.jsonl\", encoding=\"utf-8\") as f:\n    records = [json.loads(line) for line in f if line.strip()]\n```\n\n**Trailing commas and comments aren't valid JSON.** `{\"a\": 1,}` or `// comment` will raise `JSONDecodeError`. If you're stuck with such files, use the `json5` or `commentjson` package.\n\n**Huge files:** `json.load()` builds the whole structure in memory. For files that don't fit, use a streaming parser like [`ijson`](https://pypi.org/project/ijson/):\n\n```python\nimport ijson\n\nwith open(\"huge.json\", \"rb\") as f:\n    for record in ijson.items(f, \"users.item\"):\n        process(record)\n```\n\n## Writing it back out\n\nFor completeness:\n\n```python\nwith open(\"out.json\", \"w\", encoding=\"utf-8\") as f:\n    json.dump(data, f, indent=2, ensure_ascii=False)\n```\n\n`indent=2` makes it human-readable; `ensure_ascii=False` keeps non-ASCII characters as-is instead of escaping them to `\\uXXXX`."
    }
  ],
  "model": "claude-opus-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 38,
    "output_tokens": 1398,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}

</details>

Parameters

▶messages[]

arrayrequired

max_tokens

numberrequiredexclusiveMinimum: 0

system

string

stream

boolean

▶metadata{}

object

id

string

type

stringconst: message

role

stringconst: assistant

▶content[]

array

model

string

stop_reason

string

▶usage{}

object

API Schemas (Raw)

Input Open Download

Output Open Download

Was this helpful?

YesNo

On this page

data.json: {"users": [{"name": "Ada", "r - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/#page","headline":"Claude Opus 5","description":"Claude Opus 5 is Anthropic's model for complex agentic coding and enterprise work, delivering intelligence close to Claude Fable 5 at half the price. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing. Unlike Fable 5, Opus 5 has no data retention requirements for general access.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-opus-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}


description: Claude Opus 5.5 is Anthropic's model for long-running agentic coding and knowledge work. It combines a one million token context window with adaptive thinking that is always on, a 128K token maximum output, and a medium default effort level. title: Claude Opus 5.5 image: https://developers.cloudflare.com/og-docs.png


Skip to content

Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt
Use this file to discover all available pages before exploring further.

Anthropic logo