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-key

Mistral AI Free Plan: what is free and how to get a key

  1. 1Guess

    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?
  2. 2Read

    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.

  3. 3Code

    JSON mode with curl

    1 / 2
    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"}]
      }'
    

    Read the program. What will it print?

  4. 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.

  5. 5Code

    A JSON schema and a Go struct

    1 / 2
    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)
    }
    

    Read the program. What will it print?

  6. 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)
    }
    
    JSON mode is on, yet the program exits with an error. What is wrong?
  7. 7Code

    Check the fields before you trust them

    1 / 2
    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)
    	}
    }
    

    Read the program. What will it print?

  8. 8Say it back

  9. 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

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

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer