---
title: "Get JSON you can parse from a model"
slug: "json-output"
description: "Ask for JSON mode and a JSON schema, decode the reply into a Go struct, and check the fields before you trust them."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/json-output"
---

# Get JSON you can parse from a model

How do you make a model answer with JSON your program can parse, and what do you do when it does not?

## Run it against a real free API

The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.

```sh
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key
```

[Mistral AI Free Plan: what is free and how to get a key](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func chat(body map[string]any) (*http.Response, error) {
	payload, _ := json.Marshal(body)
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	return http.DefaultClient.Do(req)
}

func content(res *http.Response) string {
	defer res.Body.Close()
	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	return out.Choices[0].Message.Content
}

func main() {
	res, err := chat(map[string]any{
		"model": os.Getenv("LLM_MODEL"),
		"messages": []map[string]string{
			{"role": "user", "content": "Return JSON with the name, age and city of: Ada Lovelace, 36, lives in London"},
		},
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	var person map[string]any
	if err := json.Unmarshal([]byte(content(res)), &person); err != nil {
		fmt.Println("decode error:", err)
		return
	}
	fmt.Println(person)
}
```

The program asks a model for JSON in plain words, with no response format, and decodes the reply with json.Unmarshal. What happens?

- It prints the person as a map
- It prints a decode error, because the reply is prose around the JSON
- The server refuses the request

Answer: It prints a decode error, because the reply is prose around the JSON — The reply starts with a friendly sentence and wraps the JSON in a code fence. The first character is not a brace, so the decoder stops at once.

Output:

```
decode error: invalid character 'S' looking for beginning of value
```

_Simulated response (local mock server), 2026-12-03._

Asking nicely is not a contract. The next steps turn on the modes that make the server return only JSON.

## JSON mode

Set `response_format` to `{"type": "json_object"}` and the server returns text that is valid JSON. That is all it promises: valid syntax, not your field names. Your prompt must also ask for JSON. The OpenAI API rejects a request in JSON mode that never mentions it, and other providers follow the same rule. Say which fields you want in the prompt, and still check them after decoding.

## JSON mode with curl

```sh
curl -s "$LLM_BASE_URL/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -d '{
    "model": "'"$LLM_MODEL"'",
    "response_format": {"type": "json_object"},
    "messages": [{"role": "user", "content": "Return JSON with the name, age and city of: Ada Lovelace, 36, lives in London"}]
  }'
```

Output:

```
{
  "id": "chatcmpl-mock-0001",
  "object": "chat.completion",
  "created": 1796256000,
  "model": "mock-chat-1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"name\":\"Ada Lovelace\",\"age\":36,\"city\":\"London\"}"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 15,
    "completion_tokens": 2,
    "total_tokens": 17
  }
}
```

_Simulated response (local mock server), 2026-12-03._

The reply is still a string inside `content`. Your program decodes the response first, then decodes that string again. This is the simulated output.

## JSON schema

A stricter option is `{"type": "json_schema", "json_schema": {"name": ..., "schema": {...}}}`. You describe the keys and their types, and the model fills exactly those keys. Not every provider or model supports it, and some only support JSON mode, so check the model's documentation before you rely on it. The schema removes guessing about key names. It does not make the values true.

## A JSON schema and a Go struct

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func chat(body map[string]any) (*http.Response, error) {
	payload, _ := json.Marshal(body)
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	return http.DefaultClient.Do(req)
}

func content(res *http.Response) string {
	defer res.Body.Close()
	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	return out.Choices[0].Message.Content
}

func main() {
	res, err := chat(map[string]any{
		"model": os.Getenv("LLM_MODEL"),
		"response_format": map[string]any{
			"type": "json_schema",
			"json_schema": map[string]any{
				"name": "person",
				"schema": map[string]any{
					"type": "object",
					"properties": map[string]any{
						"name": map[string]string{"type": "string"},
						"age":  map[string]string{"type": "integer"},
						"city": map[string]string{"type": "string"},
					},
				},
			},
		},
		"messages": []map[string]string{
			{"role": "user", "content": "Return JSON with the name, age and city of: Ada Lovelace, 36, lives in London"},
		},
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	var p struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
		City string `json:"city"`
	}
	if err := json.Unmarshal([]byte(content(res)), &p); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Printf("%s is %d and lives in %s\n", p.Name, p.Age, p.City)
}
```

Output:

```
Ada Lovelace is 36 and lives in London
```

_Simulated response (local mock server), 2026-12-03._

The struct tags match the schema keys, so `json.Unmarshal` fills the fields directly.

## Fix it

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func chat(body map[string]any) (*http.Response, error) {
	payload, _ := json.Marshal(body)
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	return http.DefaultClient.Do(req)
}

func content(res *http.Response) string {
	defer res.Body.Close()
	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	return out.Choices[0].Message.Content
}

func main() {
	res, err := chat(map[string]any{
		"model":           os.Getenv("LLM_MODEL"),
		"response_format": map[string]string{"type": "json_object"},
		"messages": []map[string]string{
			{"role": "user", "content": "What are the name and age of: Ada Lovelace, 36, lives in London?"},
		},
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if res.StatusCode != http.StatusOK {
		fmt.Fprintln(os.Stderr, "request failed:", res.Status)
		os.Exit(1)
	}
	var p struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}
	json.Unmarshal([]byte(content(res)), &p)
	fmt.Println(p.Name, p.Age)
}
```

JSON mode is on, yet the program exits with an error. What is wrong?

- The prompt never mentions JSON
- The model id is wrong
- The key is missing

Answer: The prompt never mentions JSON — JSON mode requires the conversation to ask for JSON in some form. Without that word the server answers 400.

Error message:

```
request failed: 400 Bad Request
```

Fixed:

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func chat(body map[string]any) (*http.Response, error) {
	payload, _ := json.Marshal(body)
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	return http.DefaultClient.Do(req)
}

func content(res *http.Response) string {
	defer res.Body.Close()
	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	return out.Choices[0].Message.Content
}

func main() {
	res, err := chat(map[string]any{
		"model":           os.Getenv("LLM_MODEL"),
		"response_format": map[string]string{"type": "json_object"},
		"messages": []map[string]string{
			{"role": "user", "content": "Reply in JSON. What are the name and age of: Ada Lovelace, 36, lives in London?"},
		},
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if res.StatusCode != http.StatusOK {
		fmt.Fprintln(os.Stderr, "request failed:", res.Status)
		os.Exit(1)
	}
	var p struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}
	json.Unmarshal([]byte(content(res)), &p)
	fmt.Println(p.Name, p.Age)
}
```

Output:

```
Ada Lovelace 36
```

_Simulated response (local mock server), 2026-12-03._

## Check the fields before you trust them

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func chat(body map[string]any) (*http.Response, error) {
	payload, _ := json.Marshal(body)
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	return http.DefaultClient.Do(req)
}

func content(res *http.Response) string {
	defer res.Body.Close()
	var out struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	return out.Choices[0].Message.Content
}

type Person struct {
	Name *string `json:"name"`
	Age  *int    `json:"age"`
	City *string `json:"city"`
}

func main() {
	res, err := chat(map[string]any{
		"model":           os.Getenv("LLM_MODEL"),
		"response_format": map[string]string{"type": "json_object"},
		"messages": []map[string]string{
			{"role": "user", "content": "Return JSON with the name, age and city of: Ada Lovelace is 36 years old."},
		},
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	dec := json.NewDecoder(strings.NewReader(content(res)))
	dec.DisallowUnknownFields()
	var p Person
	if err := dec.Decode(&p); err != nil {
		fmt.Println("invalid JSON:", err)
		return
	}
	switch {
	case p.Name == nil:
		fmt.Println("missing field: name")
	case p.Age == nil:
		fmt.Println("missing field: age")
	case p.City == nil:
		fmt.Println("missing field: city")
	default:
		fmt.Println("ok:", *p.Name, *p.Age, *p.City)
	}
}
```

Output:

```
missing field: city
```

_Simulated response (local mock server), 2026-12-03._

The input never says where Ada lives, so `city` comes back as null. Pointer fields tell "missing" from "zero". On a failed check, retry once with the error in the prompt or reject the answer: never use it blindly.

## Say it back

In your own words: what do JSON mode and a JSON schema promise, and why do you still check the result?

Our sentence: JSON mode promises the reply is valid JSON, and a schema promises the keys I named. Neither promises the values are right or present, so I decode into a struct with pointers, check each required field, and retry once or reject when one is missing.

## Mission (12 min)

Use the free key from the offer at the top. Run the schema program against it, then the validation program with a sentence that has no city. Note what differs from the simulated output: a real model may fill a missing field with a guess instead of null.

```sh
export LLM_BASE_URL=<base URL from the offer page>
export LLM_MODEL=<model id from the offer page>
export LLM_API_KEY=<your key>
go run main.go
```

## Common questions

### What is the difference between JSON mode and a JSON schema?

JSON mode guarantees that the reply parses as JSON, but the keys and types are up to the model. A JSON schema names the keys and their types, so the reply has the shape you asked for. Both guarantee shape only. A well-formed answer can still hold a wrong age or an invented city, so validate the values that matter.

### Why does my prompt have to mention JSON?

Some providers require it in JSON mode: without the word in the conversation the request fails. The reason is practical. A model told only to use a format may fill the answer with endless whitespace. Asking for JSON in the prompt, with the fields you want, gives it a clear target and gives you a clean result.

### What should I do when the JSON is invalid or incomplete?

Retry once, adding the error to the prompt, for example "your reply was missing city". If the second try fails too, reject the answer and show an error or use a default. Do not loop without limit, because every retry costs tokens and counts against your rate limit. Log the failures so you can improve the prompt.

## Sources

- https://platform.openai.com/docs/guides/structured-outputs (read 2026-12-03)
- https://docs.mistral.ai/capabilities/structured_output/json_mode/ (read 2026-12-03)
- https://pkg.go.dev/encoding/json (read 2026-12-03)

Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03.
