Get JSON you can parse from a model
Learn LLMs · Beginner · 16 min · After Call a chat completion API with curl and Go
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.
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key1Guess
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) }2Read
JSON mode
Set
response_formatto{"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.3Code
JSON mode with curl
1 / 2curl -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"}] }'Read the program. What will it print?
4Read
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.5Code
A JSON schema and a Go struct
1 / 2package 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) }Read the program. What will it print?
6Fix
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) }7Code
Check the fields before you trust them
1 / 2package 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) } }Read the program. What will it print?
8Say it back
9Mission · 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.
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
Published Dec 3, 2026 · Updated Dec 3, 2026