GrepBoard/Manuals
605 manuals ·

Get JSON-only output from Claude when json.loads fails

·Tested on Claude Code 2.1.302 · claude -p --model sonnet · Ubuntu 24.04 · 2026-10·Test scope ↓·7 steps

Asking for "JSON" gets you a code fence and a failed parse. Rewrite the prompt with a schema and a no-extra-text rule, then check 8 runs with json.tool.

If json.loads fails with Expecting value: line 1 column 1 (char 0), look at the first character of the reply. It is usually a ``` `json ``` fence or a sentence such as "Here is the JSON".

[1] Save the input. It is a short customer inquiry, written for this test.

inquiry.txt
주문번호 A-20417 으로 지난주 화요일에 시킨 무선 키보드가 아직도 안 왔습니다. 배송 조회를 보면 3일째 "배송 준비중" 이고, 급하게 쓸 데가 있어서 이번 주 안에 못 받으면 취소하고 환불받고 싶습니다. 답변은 이메일로 주세요.

[2] Build the naive prompt first: one line asking for JSON. (It says "summarize this customer inquiry as JSON" in Korean.)

console
$ { printf '다음 고객 문의를 JSON 으로 정리해 줘.\n\n'; cat inquiry.txt; } > bad.txt

[3] Check the result with python3 -m json.tool. It prints OK on success, or the parse error and FAIL. --tools "" turns tools off and --max-turns 1 allows a single reply.

console
$ claude -p --model sonnet --max-turns 1 --tools "" < bad.txt > bad.1.txt$ python3 -m json.tool bad.1.txt > /dev/null && echo OK || echo FAILExpecting value: line 1 column 1 (char 0)FAIL

The first line was ``` `json `` and the last was `` ` ```. The body is valid JSON; those two lines break it. All 4 runs failed the same way. After stripping the fence, the key names differed from run to run:

RunFirst lineTop-level keys (first 4)
1code fenceorder_number · product · order_date · issue
2code fenceorder_number · product · order_date · order_date_note
3code fenceorder_number · product · order_date · issue_type
4code fenceorder_number · product · order_date · issue_type

[4] Rewrite the prompt. Four changes: state "a single JSON object, nothing before or after", list key names and types, limit values with |, and add one example output. Wrap the inquiry in <inquiry> tags to separate it from the instructions.

good.txt
Extract the fields below from the customer inquiry inside <inquiry>. Output a single JSON object and nothing else: no code fence, no text before or after it.Use exactly these keys and types:{"order_id": string or null, "issue": "delay" | "damage" | "refund" | "other", "wants_refund": true | false, "reply_channel": "email" | "phone" | null, "summary": string}- Do not add or rename keys. Use null when the inquiry does not say.- summary: one Korean sentence, 40 characters or fewer. Example output:{"order_id": "B-1001", "issue": "damage", "wants_refund": true, "reply_channel": "phone", "summary": "파손된 상품의 환불을 원함"} <inquiry>

[5] Append the inquiry and the closing tag, run it, and check with the same one-liner.

console
$ (cat good.txt inquiry.txt; echo "</inquiry>") > good.in.txt$ claude -p --model sonnet --max-turns 1 --tools "" < good.in.txt > good.1.txt$ python3 -m json.tool good.1.txt > /dev/null && echo OK || echo FAILOK$ cat good.1.txt{"order_id": "A-20417", "issue": "delay", "wants_refund": true, "reply_channel": "email", "summary": "배송 지연으로 이번 주 내 미수령 시 환불 원함"}

[6] Count and compare. Both prompts ran 4 times on the same input.

PromptRunsPassed json.toolFailed
bad.txt (one line)404
good.txt (schema, no-extra-text rule, example)440

All 4 improved replies had the same five keys (issue · order_id · reply_channel · summary · wants_refund), with issue = delay and wants_refund = true. Only the wording of summary differed, by one word.

[7] If the output goes into application code rather than a script, use the API's structured outputs instead of relying on the prompt. Put type: "json_schema" and your schema in output_config.format of the request, and the reply's text block contains JSON that matches the schema. claude-sonnet-5-5 is on the supported-model list and no beta header is needed. The older output_format parameter is deprecated and works only with the structured-outputs-2025-11-13 beta header.

request.json
"output_config": {  "format": {    "type": "json_schema",    "schema": {      "type": "object",      "properties": {"name": {"type": "string"}, "email": {"type": "string"}},      "required": ["name", "email"],      "additionalProperties": false    }  }}

Docs: Structured outputs · Prompt engineering

Check it with the JSON · YAML formatter and converter tool ↗ — calculated in your browser.

#claude#json#prompt