How to ensure llm return json?
- User
How to ensure llm return json?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How to ensure llm return json?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here are the most reliable ways to get consistent, valid JSON from an LLM in 2025:
Most major LLM providers now offer dedicated JSON modes:
# OpenAI example
response = client.chat.completions.create(
model="gpt-4o",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Return data as JSON only."},
{"role": "user", "content": "List 3 planets with their diameters"}
]
)
Define the exact JSON structure you want returned:
# Using OpenAI function calling
functions = [{
"name": "output_data",
"description": "Output structured data",
"parameters": {
"type": "object",
"properties": {
"planets": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"diameter_km": {"type": "number"}
}
}
}
}
}
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "List 3 planets with their diameters"}],
tools=functions,
tool_choice={"type": "function", "function": {"name": "output_data"}}
)
Return your answer as a valid JSON object with the following structure:
{
"planets": [
{"name": string, "diameter_km": number},
...
]
}
Output ONLY the JSON with no other text or explanation.
# Using instructor library with Pydantic
import instructor
from pydantic import BaseModel
from typing import List
client = instructor.patch(openai.OpenAI())
class Planet(BaseModel):
name: str
diameter_km: float
class PlanetList(BaseModel):
planets: List[Planet]
response = client.chat.completions.create(
model="gpt-4o",
response_model=PlanetList,
messages=[{"role": "user", "content": "List 3 planets with their diameters"}]
)
# Returns a PlanetList object with validated data
For when things go wrong:
import json
import json_repair
def get_valid_json(llm_response):
try:
# Try direct parsing
return json.loads(llm_response)
except json.JSONDecodeError:
try:
# Try repairing common JSON errors
fixed_json = json_repair.repair_json(llm_response)
return json.loads(fixed_json)
except:
# Last resort: extract anything between curly braces
import re
json_match = re.search(r'{.*}', llm_response, re.DOTALL)
if json_match:
try:
return json.loads(json_match.group(0))
except:
return {"error": "Failed to parse JSON"}
return {"error": "No JSON found"}
Would you like me to explain or break down any of these code examples?