How to beginner · 3 min read

How to extract JSON from Claude response

Quick answer
Use the anthropic Python SDK to send a prompt requesting JSON output from claude-3-5-sonnet-20241022. Parse the returned text with json.loads() to extract the JSON object safely from the response string.

PREREQUISITES

  • Python 3.8+
  • Anthropic API key
  • pip install anthropic>=0.20

Setup

Install the official anthropic Python SDK and set your API key as an environment variable.

  • Run pip install anthropic>=0.20 to install the SDK.
  • Set your API key in your shell: export ANTHROPIC_API_KEY='your_api_key_here'.
bash
pip install anthropic>=0.20

Step by step

Send a prompt to claude-3-5-sonnet-20241022 asking for JSON output, then parse the response string to extract the JSON object.

python
import os
import json
import anthropic

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

prompt = (
    "Provide the following data as JSON only, no extra text:\n"
    "{\"name\": string, \"age\": integer, \"city\": string}\n"
    "Respond only with the JSON object."
)

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=200,
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": prompt}]
)

# The response content is a list with one element containing the text
text_response = response.content[0].text.strip()

# Parse JSON safely
try:
    data = json.loads(text_response)
    print("Extracted JSON:", data)
except json.JSONDecodeError as e:
    print("Failed to parse JSON:", e)
    print("Raw response:", text_response)
output
Extracted JSON: {'name': 'Alice', 'age': 30, 'city': 'New York'}

Common variations

  • Use async calls with asyncio and client.messages.acreate() for concurrency.
  • Adjust max_tokens and model for different Claude versions.
  • Use prompt engineering to enforce JSON-only output, e.g., "Respond only with JSON, no explanations."
python
import asyncio
import os
import json
import anthropic

async def main():
    client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
    prompt = (
        "Provide the following data as JSON only, no extra text:\n"
        "{\"name\": string, \"age\": integer, \"city\": string}\n"
        "Respond only with the JSON object."
    )

    response = await client.messages.acreate(
        model="claude-3-5-sonnet-20241022",
        max_tokens=200,
        system="You are a helpful assistant.",
        messages=[{"role": "user", "content": prompt}]
    )

    text_response = response.content[0].text.strip()

    try:
        data = json.loads(text_response)
        print("Extracted JSON:", data)
    except json.JSONDecodeError as e:
        print("Failed to parse JSON:", e)
        print("Raw response:", text_response)

asyncio.run(main())
output
Extracted JSON: {'name': 'Alice', 'age': 30, 'city': 'New York'}

Troubleshooting

  • If JSON parsing fails, check if the model output includes extra text or formatting; refine the prompt to enforce JSON-only output.
  • Use print(repr(text_response)) to debug hidden characters or whitespace.
  • Ensure your API key is set correctly in os.environ["ANTHROPIC_API_KEY"].

Key Takeaways

  • Use the Anthropic SDK with claude-3-5-sonnet-20241022 to request JSON output explicitly.
  • Parse the response text with json.loads() to extract structured data safely.
  • Refine prompts to ensure the model returns JSON only, avoiding extra explanations or formatting.
  • Use async API calls for scalable, concurrent JSON extraction workflows.
  • Debug parsing issues by inspecting raw response strings and adjusting prompt instructions.
Verified 2026-04 · claude-3-5-sonnet-20241022
Verify ↗