{"slug": "python-json-dumps-ensure-ascii-made-my-claude-prompts-2-3x-bigger", "title": "Python json.dumps ensure_ascii Made My Claude Prompts 2.3x Bigger", "summary": "A developer running the interview-practice app Preterview traced a 2.3x token inflation in Korean-language scoring prompts to Python's json.dumps default of ensure_ascii=True, which serialized each Hangul syllable as a six-character \\uXXXX escape inside the prompt text. Replaying 500 stored scoring calls, the developer confirmed the escapes came from the app's own prompt builder rather than the Anthropic SDK, and fixed it with ensure_ascii=False plus a test that fails if \\u appears in any rendered prompt.", "body_md": "A 20-minute Korean voice session should cost about the same to score as a 20-minute English one. Mine cost more than twice as much, and for three months I assumed that was just \"how Korean tokenizes.\"\n\nIt wasn't. It was one default argument: `json.dumps` with `ensure_ascii=True`. Every Hangul syllable in my transcripts was reaching Claude as a six-character `\\uXXXX` escape, and I was paying for every one of those characters as tokens.\n\nThis post is the autopsy: how I found it, what I measured across 500 replayed scoring calls, and the two smaller bugs the fix caused.\n\n`json.dumps` defaults to `ensure_ascii=True``\\uXXXX`. One Korean syllable becomes 6 ASCII characters.` json.dumps(obj, ensure_ascii=False)`, plus a test that fails if `\\u` appears in any rendered prompt.\nThe escapes came from my own prompt builder, not from the Anthropic SDK. The scoring step takes a list of interview turns and builds a user message like this:\n\n``` php\nimport json\n\ndef build_scoring_prompt(turns: list[dict], rubric: str) -> str:\n    return (\n        f\"{rubric}\\n\\n\"\n        f\"<transcript>\\n{json.dumps(turns, indent=2)}\\n</transcript>\\n\\n\"\n        \"Score the candidate and quote their exact words as evidence.\"\n    )\n```\n\nLooks harmless. Here is what one turn actually looked like inside that string:\n\n```\n{\n  \"speaker\": \"candidate\",\n  \"text\": \"\\uc800\\ub294 \\ubc31\\uc5d4\\ub4dc \\uac1c\\ubc1c\\uc790\\ub85c 3\\ub144 \\uc77c\\ud588\\uc2b5\\ub2c8\\ub2e4\"\n}\n```\n\nThat is \"I worked as a backend developer for 3 years\" in Korean. 15 Hangul syllables became 90 characters of hex soup. The model can read it, mostly. The tokenizer, on the other hand, sees a long run of backslashes, letters and digits with no common words in it, and chops it into many small pieces.\n\nYes, but only in one specific situation: when the output of `json.dumps` ends up inside the text the model reads. With `ensure_ascii=True` (the default), any non-ASCII character becomes a `\\uXXXX` escape, and that escape costs several tokens instead of the one or two the raw character would.\n\nIt does **not** matter when JSON is just the transport. The SDK serializes your `messages` payload, the API decodes it, and the model sees real characters. I checked this first because I didn't want to chase the wrong layer:\n\n```\nclient.messages.count_tokens(\n    model=MODEL,\n    messages=[{\"role\": \"user\", \"content\": korean_answer}],  # a raw Hangul string\n)\n```\n\nSame count whether the HTTP body had escapes or not. The bug lives exactly where JSON-as-a-string meets your f-string.\n\nIt also isn't a Korean-only problem. Anything outside ASCII gets the same treatment:\n\n| Input | ensure_ascii=True | Characters | \n|---|---|---|\n| `é` | `\\u00e9` | 1 → 6 | \n| Hangul syllable (U+C800) | `\\uc800` | 1 → 6 | \n| `😀` | `\\ud83d\\ude00` | 1 → 12 | \n\nSpanish accents, Japanese, Chinese, emoji in a chat log. All of it inflates.\n\nI found it by comparing two sessions that should have been twins. One English session and one Korean session, both about 20 minutes, both roughly 30 turns. The English transcript section came in around 3,000 tokens. The Korean one was over 10,000.\n\nMy first theory was the tokenizer. Korean does usually cost more tokens per word than English, so a gap was expected. But 3x? I printed the rendered prompt instead of reading my code, and the backslashes were right there on the first screen.\n\nLesson I keep relearning: **log the final string you send, not the objects you built it from.** I had logged `turns` for months. It looked perfect, because Python prints Korean just fine. The damage only existed in the serialized form.\n\nThis pipeline is the scoring step of Preterview, an interview-practice app I run (full disclosure: I built it). After a voice session ends, the transcript plus a rubric goes to Claude, which returns scores and a written report that quotes the candidate's own answers as evidence. You can see what a session looks like at [preterview.com/en](https://preterview.com/en).\n\nTo size the damage, I took 500 stored Korean scoring requests and rebuilt each prompt twice, once with the old builder and once with `ensure_ascii=False`. Then I ran both versions through `count_tokens` and re-ran the actual scoring call on both.\n\nResults:\n\nThe overall number is lower than 3.4x because the rubric and instructions are English and were never affected. If your prompt is mostly non-ASCII user content, expect a bigger multiplier than mine.\n\nThey did, and this surprised me more than the bill. My reports quote the candidate verbatim (\"You said: ...\"). I wrote a checker that takes each quoted span and searches for it in the decoded transcript.\n\nMy read is that the model was decoding hex in its head while also scoring, summarizing and writing, and sometimes it decoded a neighbor code point. I can't prove that's the mechanism for every case, and some of the remaining 6 are plain paraphrase. But a 7x drop in misquotes from changing nothing except the encoding is hard to argue with. For a product whose whole point is \"here is exactly what you said,\" a wrong syllable is a real bug.\n\nPass `ensure_ascii=False` everywhere JSON gets embedded in prompt text:\n\n``` php\ndef to_prompt_json(obj) -> str:\n    return json.dumps(obj, ensure_ascii=False, indent=2)\n```\n\nI made it a single helper so nobody (me, at 1 a.m.) reaches for bare `json.dumps` in prompt code again. Then I added a test that renders every prompt template with a non-ASCII fixture:\n\n``` python\nimport re\n\nESCAPE = re.compile(r\"\\\\u[0-9a-fA-F]{4}\")\n\ndef test_prompts_have_no_unicode_escapes():\n    # Hangul written as escapes in source; real characters at runtime\n    turns = [{\"speaker\": \"candidate\", \"text\": \"\\uc800\\ub294 café 😀\"}]\n    for name, build in PROMPT_BUILDERS.items():\n        rendered = build(turns, rubric=\"...\")\n        assert not ESCAPE.search(rendered), f\"{name} leaked \\\\uXXXX escapes\"\n```\n\nThat fixture deliberately includes Hangul, an accented Latin letter and an emoji, because each one has caught a different code path for me.\n\nWhile you're in there, consider whether you need `indent=2` at all. Indentation is whitespace the model pays for. I kept it for the transcript because it helped the model keep speakers straight, but I dropped it from two metadata blocks where it bought nothing.\n\nTwo things, both small, both annoying.\n\n**1. A Windows file write started crashing.** A debug script dumped prompts to disk with `open(path, \"w\")`. With escapes, the content was pure ASCII and any encoding worked. Without escapes, it hit the default locale encoding on a teammate's Windows machine and raised `UnicodeEncodeError`. Fix: `open(path, \"w\", encoding=\"utf-8\")`. Always. ASCII escaping had been hiding a missing `encoding=` for months.\n\n**2. Prompt cache hit rate went to zero for about an hour.** Changing the transcript encoding changed the bytes of every prompt, so every cached prefix was invalid. Expected and harmless, but if you watch cache metrics, warn whoever gets the alert before you deploy.\n\nFor prompt text, yes. For other places, think for a second:\n\n`False` with explicit UTF-8 if you want readable logs.`True` there. That's what the default exists for.\nA quick grep finds the suspects in about ten seconds:\n\n```\ngrep -rn \"json.dumps\" --include=\"*.py\" | grep -v \"ensure_ascii=False\"\n```\n\nIn my repo that returned 14 hits. 3 of them fed prompts. The other 11 were fine as they were.\n\nBecause Python's `json.dumps` defaults to `ensure_ascii=True`, which turns every non-ASCII character into a `\\uXXXX` escape, and I was pasting that string straight into prompt text. Each Korean syllable became six ASCII characters that tokenize into several tokens, so the transcript section grew 3.4x and the whole scoring prompt grew from 4,900 to 11,400 input tokens on average. The escapes also made the model misquote candidates more often (41 vs 6 bad reports out of 500). Setting `ensure_ascii=False` for any JSON that ends up inside a prompt, plus a test that fails on `\\u` escapes in rendered prompts, fixed both problems.\n\n*Written by the developer behind [Preterview](https://preterview.com/en), an interview prep platform.*", "url": "https://wpnews.pro/news/python-json-dumps-ensure-ascii-made-my-claude-prompts-2-3x-bigger", "canonical_source": "https://dev.to/ji_ai/python-jsondumps-ensureascii-made-my-claude-prompts-23x-bigger-4k45", "published_at": "2026-11-28 09:08:57+00:00", "updated_at": "2026-11-28 09:13:33.709026+00:00", "lang": "en", "topics": ["large-language-models", "ai-tools", "developer-tools"], "entities": ["Preterview", "Anthropic", "Claude", "Python"], "also_reported_by": [], "takeaway": "Passing ensure_ascii=False to json.dumps when serializing non-ASCII text into a prompt avoids six-character \\uXXXX escapes per character, which the developer measured as 2.3x token inflation across 500 replayed Korean scoring calls.", "recommendation": {"advice": "Set ensure_ascii=False on any json.dumps output embedded in a prompt and add a test that fails if a \\u escape appears in the rendered string.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/python-json-dumps-ensure-ascii-made-my-claude-prompts-2-3x-bigger", "markdown": "https://wpnews.pro/news/python-json-dumps-ensure-ascii-made-my-claude-prompts-2-3x-bigger.md", "text": "https://wpnews.pro/news/python-json-dumps-ensure-ascii-made-my-claude-prompts-2-3x-bigger.txt", "jsonld": "https://wpnews.pro/news/python-json-dumps-ensure-ascii-made-my-claude-prompts-2-3x-bigger.jsonld"}}