EN ▾

Qwen json_object: JSON Mode for Structured Output

Set response_format to json_object, say in the prompt what keys you want, and parse the reply. The rest of this page covers the details that make it dependable in production.

Updated

Terminal emitting braces that settle into an ordered grid of cubes, illustrating structured JSON output

Key points

  • Pass response_format={"type": "json_object"} to /v1/chat/completions with model uncensored.

  • JSON mode is not a schema. Describe the keys and types in the prompt and validate the result in your code.

  • Check finish_reason: a reply cut off by max_tokens is not valid JSON.

  • Failed requests are not charged, and a JSON extraction call usually costs a fraction of a cent.

Enabling qwen json_object on this API

Searching for qwen json_object usually means one thing: you want the model to answer with a JSON object you can feed to json.loads without cleaning up markdown fences or chatty preambles. On this API that is a single request field. Add response_format with the value {"type": "json_object"} to a chat completion and the model is constrained to return a JSON object as its message content.

A note on naming. This is a hosted, OpenAI-compatible endpoint for one open-weight model, ID uncensored, run by an independent provider. It is not the official Qwen API. The request shape is the OpenAI one, which is why the same field name works with the OpenAI SDKs.

Here is the smallest working call with curl:

curl https://api.qwenimageapi.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "response_format": {"type": "json_object"},
    "messages": [
      {"role": "system", "content": "Reply only with a JSON object with keys name and age."},
      {"role": "user", "content": "Maria is thirty-four years old."}
    ]
  }'

The reply's choices[0].message.content is a string holding the object. Parse that string; do not expect the API to hand you an already-decoded object.

Python: extract, parse, validate

The pattern below is the one to copy into real code. It sets a low temperature for stable output, names the keys in the system message, parses the result and checks the fields before trusting them.

import json
from openai import OpenAI

client = OpenAI(
    base_url="https://api.qwenimageapi.com/v1",
    api_key="YOUR_KEY",
)

SYSTEM = (
    "Extract order data from the user's message. "
    "Reply with one JSON object with exactly these keys: "
    '"customer" (string), '
    '"items" (array of objects with "sku" as string and "qty" as integer), '
    '"urgent" (boolean). '
    "If a value is missing use null. Output JSON only."
)

def extract(text):
    resp = client.chat.completions.create(
        model="uncensored",
        response_format={"type": "json_object"},
        temperature=0,
        max_tokens=600,
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": text},
        ],
    )
    choice = resp.choices[0]
    if choice.finish_reason == "length":
        raise ValueError("reply was cut off, raise max_tokens")
    data = json.loads(choice.message.content)
    if not isinstance(data.get("items"), list):
        raise ValueError("items missing or wrong type")
    return data

print(extract("Anna Kowal needs 3 of AB-100 and 1 of ZX-9 as soon as possible."))

Notice that the schema lives in the prompt, in plain words and a small example of types. Writing the keys out, with their types and what to do for missing values, does most of the work of making output predictable.

Node.js version

The same call with the official OpenAI package for Node. The field names are identical, only the casing of the client options differs.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.qwenimageapi.com/v1",
  apiKey: process.env.API_KEY,
});

const resp = await client.chat.completions.create({
  model: "uncensored",
  response_format: { type: "json_object" },
  temperature: 0,
  messages: [
    { role: "system", content: "Reply with a JSON object with keys title and tags (array of strings)." },
    { role: "user", content: "Write metadata for a post about home espresso machines." },
  ],
});

const choice = resp.choices[0];
if (choice.finish_reason === "length") throw new Error("truncated");
const data = JSON.parse(choice.message.content);
console.log(data.title, data.tags);

Keep the key in an environment variable, never in client-side code. This API is meant to be called from your server or script.

What JSON mode does not do

JSON mode controls the format of the output. It does not control the content. Four limits are worth knowing before you build on it.

It is not a schema

The documented option is json_object, which means any valid object. Nothing forces a particular set of keys or types. If you need exactly customer, items and urgent, the prompt must say so, and your code must verify them. A validation library such as pydantic or zod in your own code is the right place to enforce the shape.

It can still be cut off

If the reply hits max_tokens or the context limit before the closing brace, you get broken JSON. Check finish_reason. The window is 100,000 tokens for prompt plus completion, and max_tokens is optional, so truncation is rare unless you set a small cap yourself.

Values can be wrong

A well-formed object can contain a wrong number or an invented field value. For extraction tasks, tell the model to use null for anything it cannot find, and spot-check results against source text during development.

The top level is an object

If you want a list, wrap it: ask for {"results": [...]}, not a bare array.

Settings that make output steadier

  • Temperature 0 to 0.3. Extraction and classification do not benefit from creativity.
  • A fixed seed. The seed parameter is passed through, which helps when you compare two prompt versions on the same input.
  • Mention JSON in the prompt. Say "reply with a JSON object" in the system or user message. It costs a few tokens and removes ambiguity about intent.
  • Show one example. A short sample of the expected object, with made-up values, is more precise than a paragraph of description.
  • Keep the instruction in the system message. User text often contains instructions of its own; a separate system message keeps the format request from being buried.

When the model sometimes returns a field you did not ask for, ignore it in code rather than reprompting. When it omits a field, retry once with the missing key named in the follow-up message.

JSON mode or tool calling?

Tool calling (tools and tool_choice) is also supported, with arguments returned as JSON in tool_calls. Use tools when the model should decide whether to call a function and with which arguments. Use JSON mode when every response must be a data object, as in extraction, tagging or classification. The two can live in the same app.

Debugging bad output

When parsing fails, find which of a small set of causes you are looking at. The table maps symptoms to fixes.

SymptomLikely causeFix
JSONDecodeError near the endOutput cut by max_tokensCheck finish_reason, raise the cap
Keys have different names than expectedSchema not stated in the promptList exact key names and types
Numbers returned as stringsTypes not specifiedWrite "integer" or "number" next to each key
Extra commentary around the objectNo format instructionAdd "Output JSON only" to the system message
Different shape on each callTemperature too highUse 0 to 0.3 and add one example

A reusable classification prompt

For tagging and moderation-style routing, a short, strict system message works well: "Classify the message. Reply with a JSON object with keys label (one of billing, bug, feature, other) and confidence (a number from 0 to 1)." The closed list of labels does more for consistency than any amount of explanation, and you can reject any response whose label is not on the list.

When a parse still fails after a retry, log the raw string. Reading ten failed outputs usually shows a pattern you can fix with one extra sentence in the prompt.

Streaming, retries and limits

You can combine JSON mode with stream: true, but a half-received object cannot be parsed. Collect the content deltas into a string and call the parser after the stream ends. For short objects, a non-streamed call is simpler. A streamed request keeps its concurrency slot until the stream finishes.

A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. Past a limit, the API returns HTTP 429 with the code rate_limited (too many per minute) or concurrency (too many at once). On temporary overload it also returns 429, with a Retry-After: 5 header. Respect that header in a retry loop:

import time, json
from openai import OpenAI, RateLimitError

client = OpenAI(base_url="https://api.qwenimageapi.com/v1", api_key="YOUR_KEY")

def call_json(messages, tries=4):
    for attempt in range(tries):
        try:
            r = client.chat.completions.create(
                model="uncensored",
                response_format={"type": "json_object"},
                messages=messages,
            )
            return json.loads(r.choices[0].message.content)
        except RateLimitError:
            time.sleep(5)
        except json.JSONDecodeError:
            continue
    raise RuntimeError("no valid JSON after retries")

Failed or refused requests are not charged, so retries on errors do not bill you for the failed attempt.

Cost of structured extraction

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Take the order-extraction example: a 250-token system message, a 100-token user message and a 60-token JSON reply. Input is 350 tokens: 350 x $0.15 / 1M = $0.0000525. Output is 60 tokens: 60 x $0.50 / 1M = $0.00003. Total: $0.0000825 per call. Ten thousand extractions cost $0.825, and the $0.50 trial credit covers about 6,000 of them.

Top-ups run from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200, paid in crypto (USDT on TRC20 or USDC on Base). You can claim the trial from the API key page, check rates on the pricing page, and see request and header details in the docs. For text-side work in media workflows, the integration guide shows JSON job specs in context.

A checklist before you ship

Run through these items once and your JSON calls will behave in production the way they behave on your laptop.

  1. The prompt names every key, its type and the fallback for missing values.
  2. The call sets a low temperature, and a max_tokens that comfortably fits the largest expected object.
  3. The code checks finish_reason before parsing.
  4. Parsed data passes through a validator before it touches a database or another API.
  5. Retries respect Retry-After on HTTP 429 and give up after a few attempts.
  6. You log the raw string whenever parsing fails, so you can improve the prompt from real cases.

One last point on data handling: prompts are not used for training, so extracting fields from your own text does not feed a public model. Still, treat personal data with the care your own policies require, and send only the fields the task needs.

Questions and answers

How do I turn on JSON mode?

Add response_format with the value {"type": "json_object"} to your chat completion request, and mention in the prompt which keys you want.

Does JSON mode enforce my schema?

No. It makes the reply a JSON object. Key names and types come from your prompt, so validate the parsed result in your own code.

Why do I sometimes get invalid JSON?

Usually the reply was truncated by max_tokens. Check finish_reason for length and raise the cap or shorten the output.

Can I use JSON mode with streaming?

Yes, but collect all the chunks first and parse once the stream ends, because a partial object does not parse.

Is this the official Qwen API?

No. It is an OpenAI-compatible hosted API for one open-weight model run by an independent provider, with model ID uncensored.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key