What Is JSON Mode in an LLM API and How to Use It
JSON mode is a request setting that tells a chat model to reply with a single valid JSON object instead of free text. It is what you turn on when program code, not a person, will read the answer.
Updated

Key points
- JSON mode is switched on with response_format set to json_object in a chat completions request.
- It makes the reply parseable JSON, but it does not enforce your field names, so describe them in the prompt.
- Always parse inside try/except, check for a cut-off reply, and validate the fields you need.
- Pair it with a low temperature for extraction and classification jobs.
JSON mode in plain terms
What is JSON mode? It is an option on a chat completions request. When you set response_format to {"type": "json_object"}, the model is constrained to produce a reply that is one valid JSON object. No greeting, no "Sure, here is your data", no markdown fence around it. You can pass the string straight into json.loads.
Without it, models often wrap JSON in prose or code fences, add a trailing comment, or drop a closing brace. Each of those breaks a parser at 3 a.m. JSON mode removes the most common of these failures at the source, which is why it is the first thing to try for extraction, tagging, classification and any pipeline step that feeds another program.
Our API supports it as part of the OpenAI-compatible interface, so the same request body you may have used elsewhere works here with a different base URL and the model ID uncensored.
Turn it on: curl and Python
The setting sits next to messages in the request body:
curl https://api.contentmoderationapis.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"temperature": 0,
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": "Reply only with a JSON object with keys sentiment (positive, neutral or negative) and score (0 to 1)."},
{"role": "user", "content": "The delivery was late but support fixed it fast."}
]
}'
The same call with the OpenAI Python SDK:
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.contentmoderationapis.com/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
temperature=0,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with a JSON object with keys sentiment (positive, neutral or negative) and score (0 to 1)."},
{"role": "user", "content": "The delivery was late but support fixed it fast."},
],
)
data = json.loads(resp.choices[0].message.content)
print(data["sentiment"], data["score"])
Both examples name the keys and the allowed values in the system message. That detail matters more than the flag itself, as the next section explains.
What JSON mode does not do
This is the point people miss. JSON mode guarantees the shape of the text, not the shape of your data. The model does not receive a schema. If your prompt never says which keys you want, you will get valid JSON with keys of the model's choosing, and they may change from one call to the next.
So treat the prompt as the schema. Spell out:
- every key name, exactly as your code will read it;
- the type of each value (string, integer, array of strings);
- the allowed values for enumerations;
- what to put when a value is unknown, for example
null.
It also does not stop a reply from being cut off. If the output reaches your max_tokens cap or the context limit, the JSON can end mid-string. Check finish_reason on the choice; a value of length means the reply was truncated and should not be parsed as complete. Our context window is 100,000 tokens for prompt plus completion, and max_tokens is optional, so truncation is rare unless you set a low cap yourself.
Write prompts that return clean data
A reliable pattern has three parts: a role line, the schema in words, and one short example. Give the example as a literal object so the model copies the layout.
You extract contact data from messages.
Reply with one JSON object with these keys:
"name": string or null
"email": string or null
"topics": array of up to 3 short strings
Example: {"name": "Dana", "email": "[email protected]", "topics": ["refund"]}
A few habits that help:
- Use
temperature0 to 0.2 for extraction. High temperature adds variety you do not want in a data pipeline. - Keep the document to analyze in the user message and the rules in the system message.
- Ask for flat objects when you can. Deeply nested structures have more places to go wrong.
- For lists, wrap them in an object such as
{"items": [...]}. JSON mode produces an object, so a bare top-level array is not what you should expect.
Common use cases
JSON mode earns its keep in a few repeatable jobs. Each one has the same shape: unstructured text goes in, a small record comes out.
- Extraction. Pull names, dates, amounts and addresses out of emails or support tickets into fields your database understands.
- Classification. Label a message with one category from a fixed list, plus a confidence number or a short reason a reviewer can read.
- Story and game data. Generate character sheets, item lists or quest outlines as objects your game engine loads directly. This is common in fiction tools for adults, where the text itself is the product and the JSON is the scaffolding around it.
- Agent steps. Make an intermediate step return a plan, such as
{"next_action": "search", "query": "..."}, which your loop reads and executes.
In every case, keep the record small. The shorter the object, the less can go wrong and the less you pay for output tokens at $0.50 per 1M.
Parse and validate on your side
Never trust a model reply as input to the rest of your system. Parse it inside a guard, check the fields, and retry once on failure.
import json
import os
from openai import OpenAI
REQUIRED = {"sentiment", "score"}
client = OpenAI(
base_url="https://api.contentmoderationapis.com/v1",
api_key=os.environ["API_KEY"],
)
def ask(text, retries=1):
for attempt in range(retries + 1):
resp = client.chat.completions.create(
model="uncensored",
temperature=0,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with JSON with keys sentiment and score."},
{"role": "user", "content": text},
],
)
choice = resp.choices[0]
if choice.finish_reason == "length":
continue
try:
data = json.loads(choice.message.content)
except json.JSONDecodeError:
continue
if REQUIRED.issubset(data):
return data
return None
In larger projects, validate with Pydantic or JSON Schema instead of a hand-written key check. That gives you type checks and clear error messages, and the same model class can double as the schema description you paste into the prompt.
Retries cost tokens, but failed or refused requests are not charged, and a retry of a good request is a normal request at the usual price. See the pricing page for the rates.
JSON mode, tool calling or plain prompting
There are three ways to get structured data from a chat model. They suit different jobs.
| Approach | Best for | Watch out for |
|---|---|---|
| JSON mode | Extraction, tagging, classification, fixed-shape reports | Keys come from your prompt, not a schema |
| Tool calling | Letting the model choose an action and its arguments | You must run the function and return the result as a tool message |
| Plain prompt, parse text | Quick experiments | Fences, prose and broken syntax |
Both JSON mode and tool calling are available on our API. If you only need a record back, JSON mode is simpler: one request, one object. If the model should decide among several functions, use tools. Both are described on the docs page.
JSON mode combines well with streaming, but you cannot parse a partial object, so collect the chunks and parse after the stream ends. Remember that a streamed request holds its concurrency slot until the end, which matters if you run eight jobs at once on a full key.
Try it with the trial credit
A structured extraction call is small. Take 300 input tokens and 60 output tokens per record. Input cost: 300 / 1,000,000 x $0.15 = $0.000045. Output cost: 60 / 1,000,000 x $0.50 = $0.00003. Total: $0.000075 per record. The $0.50 trial credit covers about 6,666 records of that size.
New users can claim that credit with one click on the API key page after sign-up. It needs no card and is valid for 7 days. A trial key allows 2 concurrent requests and 60 per minute, which is plenty for testing prompts before you scale a pipeline.
More guides
Questions and answers
What is JSON mode in simple words?
It is a request option that makes the model answer with one valid JSON object instead of free text, so your code can parse the reply directly.
Does JSON mode enforce my schema?
No. It ensures valid JSON syntax, but the key names and types come from your prompt. Describe the fields clearly and validate the result in code.
Can I use JSON mode with streaming?
Yes, but a partial object is not valid JSON. Collect all chunks and parse once the stream has finished.
Why is my JSON reply cut off?
The completion likely hit a token cap. Check finish_reason for length, raise or remove max_tokens, and ask for shorter values.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.