# How to get valid JSON from Claude, ChatGPT or Gemini

Your app asks an AI for JSON, and it works nine times out of ten. The tenth time, the app shows raw text, or crashes on `JSON.parse`. Here's a real answer we got from Claude, inside an app that asked for a reply and a list of changes:

```
{"type": "add_note", "item_key": "p0b", "kind": "ːIdea".replace("ː", ""), ...
```

Claude wrote a bit of code where a plain value belonged. Everything around it was fine. One expression made the whole answer unreadable.

Asking nicely in the prompt ("reply with valid JSON only") doesn't fix this. **Structured output** does: you give the AI service a JSON Schema, and it guarantees the answer matches. Claude, OpenAI and Gemini all have it.

![Asking for JSON in the prompt usually works but sometimes breaks. Structured output with a schema always returns JSON that matches it.](/blog/images/valid-json-structured-output.svg)

## Claude

Use `output_config.format` with a `json_schema`. The answer's text is then JSON that matches your schema:

```json
POST https://api.anthropic.com/v1/messages
{
  "model": "claude-opus-5-5",
  "max_tokens": 4000,
  "messages": [{ "role": "user", "content": "Suggest three video ideas." }],
  "output_config": {
    "format": {
      "type": "json_schema",
      "schema": {
        "type": "object",
        "properties": {
          "reply": { "type": "string" },
          "ideas": { "type": "array", "items": { "type": "string" } }
        },
        "required": ["reply", "ideas"],
        "additionalProperties": false
      }
    }
  }
}
```

Every object in the schema needs `"additionalProperties": false`. Some checks, like `minLength` or `maximum`, aren't enforced by the API, so check those in your own code.

**Watch out for an old trick.** Code written for earlier Claude models often forced a tool call to get JSON: `"tool_choice": {"type": "tool", "name": "respond"}`. Newer models, including Claude Sonnet 5.5 and Opus 5.5, reject forced tool choice with a 400 error. If your app did this and Claude suddenly "refuses the request", that's why. Use `output_config.format`, or a tool with `"strict": true` and `tool_choice` left as `auto`.

## OpenAI

Use `response_format` with a `json_schema` and `strict: true`:

```json
"response_format": {
  "type": "json_schema",
  "json_schema": {
    "name": "answer",
    "strict": true,
    "schema": { "type": "object", "properties": { "reply": { "type": "string" } },
                "required": ["reply"], "additionalProperties": false }
  }
}
```

The older `{"type": "json_object"}` only promises *some* JSON, not your shape. Prefer the schema.

## Gemini

In Gemini's own API, set the response type and schema in `generationConfig`:

```json
"generationConfig": {
  "responseMimeType": "application/json",
  "responseSchema": { "type": "object", "properties": { "reply": { "type": "string" } },
                      "required": ["reply"] }
}
```

Through Google's OpenAI-compatible endpoint, use the same `response_format` as OpenAI.

## It still isn't the end of checking

A schema guarantees the *shape*, not that the content is right. The AI can still:

- refer to an item that doesn't exist
- pick a value your app doesn't allow, if the schema is loose
- stop early because it hit `max_tokens`, or decline the request

So check the answer before saving anything: known types only, IDs that exist, lengths within your limits. And look at the stop reason: on Claude, `max_tokens` means the answer was cut off, and `refusal` means it declined.

If the result changes your data, show it to the person first and let them apply it. [That pattern is here](/blog/add-ai-assistant-to-your-app).

## Tell your agent

"Wherever we ask an AI for JSON, use the provider's structured output with a JSON Schema instead of asking in the prompt. Don't force tool_choice for Claude. Validate the parsed result before saving it."

On Toupas, chats that build apps are already told to do this.

## Questions

### Why does Claude return invalid JSON?

When JSON is only asked for in the prompt, the model can slip, for example by writing code or text where a value belongs. Use structured output (`output_config.format`) to guarantee valid JSON.

### How do I force JSON output from ChatGPT?

Use `response_format` with `type: "json_schema"` and `strict: true`. The older `json_object` mode returns JSON but not necessarily your shape.

### Why does tool_choice return a 400 error with Claude?

Newer Claude models, including Sonnet 5.5 and Opus 5.5, don't accept a forced tool choice. Use structured output, or a strict tool with `tool_choice` set to `auto`.

### Does structured output mean I don't need to validate?

No. It guarantees the shape. You still check the values, and the stop reason, before saving anything.
