EN ▾
NSFW Image API

Uncensored text API for NSFW pipelines

Get API key
uncensoredapi.nsfwimage.top/v1

What Is JSON Text? How to Get It From an LLM API

JSON text is a plain string that follows a strict format for data. Language models are good at writing it once you switch on JSON mode, and this page shows how.

Updated

Glowing curly brackets unpacking into tidy drawers of data blocks, representing structured JSON output

Key points

#01
  • JSON text is a string of keys, values, arrays and objects written to a fixed set of rules that any language can parse.
  • Set response_format to {"type": "json_object"} and describe the shape you want in the prompt.
  • Always parse the reply with a real JSON parser and handle failure, since a truncated reply is not valid JSON.
  • Use tool calling when you need arguments for a function rather than a free-form document.
uncensored#02

What JSON text is

If you are asking what is json text, here is the direct answer. JSON stands for JavaScript Object Notation. It is a way of writing structured data as plain text so that programs written in different languages can exchange it. A piece of JSON text is just a string, and what makes it JSON is that it follows the format rules exactly.

Here is a small example describing a scene for a prompt-writing tool:

{
  "title": "Harbor at dusk",
  "tags": ["fantasy", "market", "lanterns"],
  "length_words": 120,
  "needs_review": false,
  "notes": null
}

That is an object with five keys. The values show every basic type JSON has: a string, an array, a number, a boolean and null. The only other type is a nested object. Everything else you may want to store, such as dates, has to be written as one of these, usually a string.

The rules that trip people up

JSON is stricter than the code it was named after. Most parsing errors come from a short list of mistakes.

  • Keys and strings use double quotes. Single quotes are invalid.
  • No trailing commas after the last item in an object or array.
  • No comments of any kind.
  • Booleans and null are lowercase: true, false, null. Python-style True and None are invalid.
  • Inside strings, a double quote, a backslash and line breaks must be escaped.
  • The whole text must be one value. Two objects back to back, or a sentence before the opening brace, make it invalid.

The last rule is the one that matters for language models. A model asked for data will often add a friendly sentence first or wrap the data in a Markdown code fence. Your parser sees that sentence and fails. Everything below is about removing that failure mode.

Why ask a model for JSON at all

Free text is hard for software to use. If a bot writes a character profile as a paragraph, your code has to guess where the name ends and the traits begin. If it returns JSON, you read data["name"] and move on. Typical jobs include extracting fields from messy user input, tagging and classifying messages, producing several variants of a short text in a list, and filling a template for a downstream tool.

If you build a pipeline around an image generator, a text model can turn a loose idea into structured fields such as subject, setting, lighting and style, which your code then assembles into the prompt for the image service. This API handles the text step only; it does not generate images. The article on image generation APIs explains how the two pieces fit together.

Turning on JSON mode

The endpoint is OpenAI-compatible, so JSON mode is the usual parameter: response_format set to {"type": "json_object"}. Use the model ID uncensored and your base URL. Also say in the prompt what keys you want. The setting steers the output toward valid JSON, but only your prompt can tell the model which fields to produce.

import json
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    temperature=0.2,
    messages=[
        {"role": "system", "content": (
            "Reply with a single JSON object with keys: "
            "subject (string), setting (string), mood (string), tags (array of strings)."
        )},
        {"role": "user", "content": "An old lighthouse keeper repairing a lamp during a storm."},
    ],
)

raw = resp.choices[0].message.content
data = json.loads(raw)
print(data["subject"], data["tags"])

The same call in curl:

curl https://api.nsfwimage.top/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 with a JSON object with keys name and mood."},
      {"role": "user", "content": "A quiet night market."}
    ]
  }'

Parse defensively

Even with JSON mode on, treat the reply as untrusted input. Wrap the parse in a try block, check the keys you need, and decide what happens on failure. A short retry loop is usually enough.

import OpenAI from "openai";

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

async function getProfile(idea) {
  for (let attempt = 0; attempt < 3; attempt++) {
    const res = await client.chat.completions.create({
      model: "uncensored",
      response_format: { type: "json_object" },
      messages: [
        { role: "system", content: "Return JSON with keys name (string) and traits (array of strings)." },
        { role: "user", content: idea },
      ],
    });
    const choice = res.choices[0];
    if (choice.finish_reason === "length") continue;
    try {
      const data = JSON.parse(choice.message.content);
      if (typeof data.name === "string" && Array.isArray(data.traits)) return data;
    } catch (err) {
      // fall through and retry
    }
  }
  throw new Error("no valid JSON after 3 attempts");
}

The check on finish_reason catches the most common real-world failure. If the output hits the token limit mid-object, you get a cut-off string, and no parser can repair it. Leave max_tokens unset or generous when you expect JSON, since the completion can use the rest of the 100,000-token window. A retry costs only the tokens it uses; a typical small extraction costs a fraction of a cent at $0.15 per 1M input tokens and $0.50 per 1M output tokens.

Common failures and fixes

SymptomLikely causeFix
Parser fails at the first characterProse or a code fence before the objectTurn on JSON mode and state "JSON object only" in the system message
Parser fails at the endOutput cut off by a length limitCheck finish_reason, raise or remove max_tokens
Keys differ between callsThe prompt names no keysList exact key names and types in the prompt
Numbers arrive as stringsAmbiguous instructionSay "number, not string" and show one example
Values are inconsistentHigh temperatureUse a low temperature such as 0.2, or set a seed for repeatable tests

An example object inside the prompt helps more than a long description. Show the model one filled-in sample and tell it to follow the same keys.

A worked extraction from start to finish

To make this concrete, suppose a support bot receives messages like "Order 4821 arrived broken, I want a replacement by Friday" and needs fields it can store. The prompt names three keys: order_id as a string, intent as one of a short list of labels, and deadline as a string or null. You send the message as the user turn, the key list as the system turn, and JSON mode on.

The reply comes back as one object with those keys. Your code parses it, checks that intent is in the allowed list, and stores the fields. If the label is outside the list, treat it as a failed attempt and retry once with a stricter reminder. This pattern, ask then verify, scales from tiny bots to batch jobs over thousands of rows.

Cost stays small. A 300-token prompt and a 60-token reply is 300 x $0.15 / 1M plus 60 x $0.50 / 1M, which is $0.000045 plus $0.00003, or $0.000075. For 10,000 rows that is $0.75. Doing the same extraction with regular expressions would take far longer to write and break on every new phrasing.

JSON mode, tool calling, or plain text

Pick by what your code does next. Use JSON mode when you want a document: a profile, a list of tags, an extraction result. Use tool calling when you want the model to choose a function and fill its arguments. The API accepts tools and tool_choice in the standard format, returns tool_calls (also when streaming), and expects your function results back as messages with role: "tool". Use plain text when a human reads the result and structure adds nothing.

You can combine them: a tool call carries its arguments as a JSON string, so everything above about parsing applies to function.arguments too.

To try this without spending anything, claim the $0.50 trial credit on the key page (one per person, valid for 7 days, no card). The quickstart lists every supported parameter, and the pricing page has the details of top-ups from $20, paid in USDT on TRC20 or USDC on Base.

Questions and answers

#03
Is JSON text the same as a JavaScript object?

No. JSON text is a string that follows strict rules, such as double-quoted keys. A JavaScript object lives in memory; you convert between them with JSON.parse and JSON.stringify.

Does JSON mode guarantee my schema?

It pushes the output toward valid JSON, but your prompt must name the keys and types. Always validate the parsed result in your own code.

Why does my parse fail on a long reply?

The output was probably cut off by a token limit. Check finish_reason, and avoid a tight max_tokens when you expect a large object.

Can I stream JSON output?

Yes, streaming works over SSE, but you can only parse once the full text has arrived. Collect the chunks, then parse the joined string.

Your key is one form away

#04

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