Load data from the string

data = json.loads(json_string)

print(data['city']) # Output: New York

````

```json
{
  "candidates": [
    {
      "avgLogprobs": -0.18925412299094185,
      "content": {
        "parts": [
          {
            "text": "Of course! Reading a JSON file in Python is a common task, and the built-in `json` module makes it very straightforward.\n\nHere is the most common and recommended way to do it.\n\n### The Short & Sweet Answer\n\nUse the `json.load()` function along with a `with open()` context manager.\n\n```python\nimport json\n\n# The name of your JSON file\nfilename = 'data.json'\n\n# Use a 'with' statement for safe file handling\nwith open(filename, 'r') as file:\n    # Load the JSON data from the file into a Python object\n    data = json.load(file)\n\n# Now 'data' is a Python dictionary (or list) that you can work with\nprint(\"Successfully loaded JSON data!\")\nprint(data)\n\n# Example of accessing data\nprint(\"\\nAccessing specific data:\")\nprint(\"Name:\", data['name'])\nprint(\"First skill:\", data['skills'][0])\n```\n\n---\n\n### Step-by-Step Explanation\n\nLet's break down the code above with a complete, runnable example.\n\n#### 1. Create a Sample JSON File\n\nFirst, let's create a JSON file to read. Save the following content in a file named `data.json` in the same directory as your Python script.\n\n**`data.json`**\n```json\n{\n  \"name\": \"Alex\",\n  \"id\": 12345,\n  \"is_active\": true,\n  \"email\": null,\n  \"skills\": [\n    \"Python\",\n    \"Data Analysis\",\n    \"Machine Learning\"\n  ],\n  \"projects\": {\n    \"project_a\": \"In Progress\",\n    \"project_b\": \"Completed\"\n  }\n}\n```\n> **Note:** JSON requires double quotes `\"` for all keys and string values. Single quotes `'` will cause an error.\n\n#### 2. Write the Python Script\n\nNow, let's look at the Python code in detail.\n\n**`read_file.py`**\n```python\n# Step 1: Import the json module\n# This module is built into Python, so no installation is needed.\nimport json\n\n# Step 2: Open the JSON file for reading\n# The 'with' statement is highly recommended because it automatically\n# handles closing the file, even if errors occur.\n# 'r' stands for \"read mode\".\nwith open('data.json', 'r') as f:\n    \n    # Step 3: Load the data using json.load()\n    # The json.load() function reads from a file-like object (f),\n    # parses the JSON data, and converts it into a Python object.\n    data = json.load(f)\n\n# Step 4: Work with your new Python object\n# The 'data' variable now holds the content of the JSON file.\n# JSON objects are converted to Python dictionaries.\n# JSON arrays are converted to Python lists.\n\nprint(\"The data type is:\", type(data))\nprint(\"---\")\nprint(\"Full data:\", data)\nprint(\"---\")\n\n# You can now access the data just like any other Python dictionary\nprint(\"User's name:\", data['name'])\nprint(\"User's skills:\", data['skills'])\n\n# Loop through the list of skills\nprint(\"\\nSkills:\")\nfor skill in data['skills']:\n    print(\"-\", skill)\n```\n\n#### How JSON Types Map to Python Types\n\nWhen you use `json.load()`, the data is converted as follows:\n\n| JSON | Python |\n| :--- | :--- |\n| object | `dict` |\n| array | `list` |\n| string | `str` |\n| number (int) | `int` |\n| number (real) | `float` |\n| `true` | `True` |\n| `false` | `False` |\n| `null` | `None` |\n\n---\n\n### Common Issues and Solutions\n\n1.  **`FileNotFoundError`**: This happens if Python can't find your file.\n    *   **Solution**: Make sure the file name is spelled correctly and the file is in the same directory as your script. If it's in a different directory, provide the full or relative path (e.g., `'data/my_file.json'`).\n\n2.  **`json.JSONDecodeError`**: This means your file is not valid JSON.\n    *   **Solution**: Check your `.json` file for syntax errors. The most common mistakes are:\n        *   Using single quotes (`'`) instead of double quotes (`\"`).\n        *   Having a trailing comma after the last item in an object or list.\n        *   Missing commas between elements.\n\n3.  **Character Encoding Issues**: If your file contains special characters (like `é` or `ü`), you might get a `UnicodeDecodeError`.\n    *   **Solution**: Specify the encoding when opening the file. UTF-8 is the most common and is standard for JSON.\n    ```python\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\n    ```\n\n### Reading a JSON String vs. a JSON File\n\nIt's important to know the difference between `json.load()` and `json.loads()`.\n\n*   `json.load()`: Reads from a **file object**.\n*   `json.loads()`: Reads from a **string**. (The 's' stands for \"string\").\n\n**Example using `json.loads()`:**\n\n```python\nimport json\n\njson_string = \"\"\"\n{\n  \"name\": \"Brenda\",\n  \"city\": \"New York\"\n}\n\"\"\"\n\n# Load data from the string\ndata = json.loads(json_string)\n\nprint(data['city'])  # Output: New York\n```"
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "createTime": "2026-04-28T19:34:08.614146Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-pro",
  "responseId": "sAvxaYK-JZmA6tkPxraQ6Qg",
  "usageMetadata": {
    "candidatesTokenCount": 1292,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 1292
      }
    ],
    "promptTokenCount": 20,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "thoughtsTokenCount": 1582,
    "totalTokenCount": 2894,
    "trafficType": "ON_DEMAND"
  }
}

</details>

<details>

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

const response = await env.AI.run(
  'google/gemini-2.5-pro',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'
Of course! The drive from San Francisco to Los Angeles offers two very different experiences, depending on
{
  "candidates": [
    {
      "avgLogprobs": -5.178282888312089,
      "content": {
        "parts": [
          {
            "text": "Of course! The drive from San Francisco to Los Angeles offers two very different experiences, depending on"
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "createTime": "2026-04-28T19:34:34.916567Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-pro",
  "responseId": "ygvxadf4N5TIodAPqsDhyQk",
  "usageMetadata": {
    "candidatesTokenCount": 19,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 19
      }
    ],
    "promptTokenCount": 64,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 64
      }
    ],
    "thoughtsTokenCount": 477,
    "totalTokenCount": 560,
    "trafficType": "ON_DEMAND"
  }
}

</details>

<details>

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

const response = await env.AI.run(
  'google/gemini-2.5-pro',
  {
    contents: [
      {
        parts: [{ text: 'Write a short story opening about a detective finding an unusual clue.' }],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 1500, temperature: 0.8 },
  },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-2.5-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a short story opening about a detective finding an unusual clue."
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 1500,
      "temperature": 0.8
    }
  }
}'
The stale, metallic tang of blood was the first
{
  "candidates": [
    {
      "avgLogprobs": -7.117010498046875,
      "content": {
        "parts": [
          {
            "text": "The stale, metallic tang of blood was the first"
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS"
    }
  ],
  "createTime": "2026-04-28T19:34:36.902347Z",
  "gatewayMetadata": {
    "keySource": "BYOK"
  },
  "modelVersion": "gemini-2.5-pro",
  "responseId": "zAvxacuJN-fHodAP8o2RyQ4",
  "usageMetadata": {
    "candidatesTokenCount": 10,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 10
      }
    ],
    "promptTokenCount": 13,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 13
      }
    ],
    "thoughtsTokenCount": 286,
    "totalTokenCount": 309,
    "trafficType": "ON_DEMAND"
  }
}

</details>

Parameters

Schema variant

Generate ContentChat Completions

▶contents[]

arrayrequired

▶systemInstruction{}

object

▶generationConfig{}

object

▶safetySettings[]

array

▶tools[]

array

toolConfig

▶messages[]

arrayrequired

temperature

numberminimum: 0maximum: 2

max_tokens

numberexclusiveMinimum: 0

max_completion_tokens

numberexclusiveMinimum: 0

top_p

numberminimum: 0maximum: 1

frequency_penalty

numberminimum: -2maximum: 2

presence_penalty

numberminimum: -2maximum: 2

stream

boolean

▶stream_options{}

object

▶tools[]

array

tool_choice

response_format

▶modalities[]

array

▶audio{}

object

reasoning_effort

stringOptional reasoning control; availability and accepted values are model-dependent.

▶candidates[]

array

▶usageMetadata{}

object

modelVersion

string

id

string

object

string

created

number

model

string

▶choices[]

array

▶usage{}

object

API Schemas (Raw)

Input Open Download

Output Open Download

Was this helpful?

YesNo

On this page

Load data from the string - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/#page","headline":"Gemini 2.5 Pro","description":"Google's most capable Gemini 2.5 model with strong reasoning, thinking support, and a 1M token context window.","url":"https://developers.cloudflare.com/ai/models/google/gemini-2.5-pro/","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: Gemini 3 Flash is Google's fast multimodal model with frontier intelligence, superior search, and grounding capabilities. title: Gemini 3 Flash 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.

Google logo