TATECHATLAS
◎ English
Artificial intelligence / Guide

Handling Control Characters in Model JSON Output

This article explains how to address control characters emitted by language models in JSON output, detailing the default strict mode in Python's json.loads and strategies for graceful degradation when encountering these characters.

On this page

Language models sometimes output JSON strings containing literal control characters (U+0000 to U+001F). Python’s json.loads function, by default, enforces strict JSON syntax, rejecting these characters. To handle this, you can disable strict mode (json.loads(raw, strict=False)), but this sacrifices JSON validation and potential detection of upstream issues. A recommended approach is to attempt parsing with strict mode first and, if it fails, retry with strict=False as a fallback.

Why model JSON output contains raw control characters

Language models, when generating text, occasionally include literal characters within JSON string values. These characters fall within the U+0000 to U+001F range, which represent control characters like tabs, newlines, and carriage returns. RFC 7159, the standard for JSON, mandates that these control characters must be represented by escape sequences, not as raw bytes within the string.

This behavior arises because language models often bypass the JSON encoder and directly output text, including these control characters, before it is processed by the JSON library. In the example above, the raw string contains a literal tab character between 'hello' and 'world'. When you print the repr, you can see the tab is embedded as an actual whitespace byte rather than the two-character escape sequence \t that valid JSON requires.

import json

# Simulate model output containing a literal tab (U+0009) inside a string value
raw = '{"message": "hello\tworld"}'
print(repr(raw))  # '{"message": "hello\tworld"}'
# The repr shows \t as two characters (backslash + t), confirming a literal tab is embedded.

Implement a two-pass strategy: first, attempt strict parsing, and if it fails, gracefully fall back to lenient parsing. This balances JSON compliance with the ability to handle model quirks.

What the strict parameter controls in JSONDecoder

The strict parameter in Python's json.loads function controls how the decoder handles control characters. When strict is set to True (the default), the decoder treats unescaped control characters as a syntax error, preventing the parsing process from continuing. This behavior aligns with RFC 7159.

Conversely, when strict is set to False, the decoder allows control characters within strings, effectively ignoring the RFC's requirement for escape sequences. In the example, strict=True raises a JSONDecodeError with the message 'Invalid control character at', while strict=False returns the parsed dictionary with the literal tab preserved in the string value.

import json

raw = '{"message": "hello\tworld"}'

# strict=True (default): raises JSONDecodeError
try:
    json.loads(raw, strict=True)
except json.JSONDecodeError as e:
    print(f"strict=True failed: {e}")

# strict=False: succeeds
result = json.loads(raw, strict=False)
print(f"strict=False result: {result}")

Why strict=True is the default and what RFC 7159 requires

The default setting of strict=True reflects a conservative approach to JSON parsing, prioritizing strict adherence to the RFC. This ensures that the decoded JSON conforms precisely to the specification, minimizing potential compatibility issues.

RFC 7159 explicitly states that control characters within strings must be represented by escape sequences (for example, \t for a tab). Python's json module defaults to enforcing this rule, rejecting JSON that does not comply. The example demonstrates that json.dumps correctly escapes the tab character into the two-character sequence \t, producing valid JSON that round-trips through json.loads without error.

import json

# The encoder always escapes control characters, producing valid JSON
original = "hello\tworld"
encoded = json.dumps(original)
print(f"Encoded: {encoded}")  # "hello\tworld" (with literal backslash-t)

# Round-trip works because the encoder produces compliant output
assert json.loads(encoded) == original

The JSONDecodeError raised when strict mode encounters a control character

When strict=True and a control character is encountered, json.loads raises a json.JSONDecodeError. This exception provides valuable information for debugging, including the error message, the document being parsed, the position of the error, and the line and column number where the error occurred.

The pos attribute of the JSONDecodeError object indicates the starting position of the error within the input string, allowing you to pinpoint the offending control character. In the example output, msg is 'Invalid control character at', pos points to the index of the tab byte, and lineno and colno (added in Python 3.5) give the human-readable location.

import json

raw = '{"message": "hello\tworld"}'

try:
    json.loads(raw, strict=True)
except json.JSONDecodeError as e:
    print(f"msg:    {e.msg}")
    print(f"doc:    {e.doc[:30]}...")
    print(f"pos:    {e.pos}")
    print(f"lineno: {e.lineno}")
    print(f"colno:  {e.colno}")

Setting strict=False as a recovery strategy for model output

To accommodate model output that occasionally contains raw control characters, you can temporarily disable strict mode by setting strict=False during parsing. This allows the parser to proceed even if the JSON doesn't strictly conform to the RFC.

This strategy is particularly useful when dealing with models that are known to emit these characters, providing a pragmatic solution without sacrificing complete JSON validation.

import json

raw = '{"message": "hello\tworld"}'

# Recovery: parse with strict=False when the model emits raw control chars
result = json.loads(raw, strict=False)
print(f"Parsed message: {repr(result['message'])}")
# Output: 'hello\tworld'  (literal tab preserved in the Python string)

Interaction with ensure_ascii on the encoding side

The ensure_ascii parameter in json.dumps controls whether non-ASCII characters are escaped. When ensure_ascii=True (the default), all non-ASCII characters are escaped using \uXXXX sequences. When ensure_ascii=False, non-ASCII characters are output as-is. However, regardless of the ensure_ascii setting, control characters in the U+0000 through U+001F range are always escaped by the encoder because the JSON specification requires it.

This means that json.dumps will never produce raw control characters in its output. The problem arises when a language model bypasses the encoder entirely and emits raw text containing literal control characters. In that scenario, the strict mode check in json.loads is what catches the violation, not any encoding-side safeguard.

import json

original = "hello\tworld"

# ensure_ascii=True (default): tab is escaped to \\t in the JSON output
print(json.dumps(original))  # "hello\tworld"

# ensure_ascii=False: tab is still escaped because control characters
# U+0000 through U+001F must always be escaped per the JSON spec
print(json.dumps(original, ensure_ascii=False))  # "hello\tworld"

# Non-ASCII characters differ between the two modes
unicode_str = "caf\u00e9"
print(json.dumps(unicode_str))  # "caf\u00e9"  (escaped)
print(json.dumps(unicode_str, ensure_ascii=False))  # "café"  (literal)

Trade-offs of disabling strict mode

Disabling strict mode introduces a narrow but important trade-off. It only relaxes the control-character check inside JSON strings. All other JSON syntax rules remain enforced. As the example shows, trailing commas and unquoted keys still raise JSONDecodeError even with strict=False.

This means strict=False is not a general-purpose lenient parser. It specifically permits raw characters in the U+0000 to U+001F range inside string values. The lenient decoder becomes more permissive than the RFC only in this one dimension, potentially accepting input that other JSON parsers would reject for the same reason.

import json

# strict=False does NOT relax other JSON syntax rules
# Trailing commas are still invalid:
try:
    json.loads('{"a": 1,}', strict=False)
except json.JSONDecodeError as e:
    print(f"Trailing comma still fails: {e.msg}")

# Unquoted keys are still invalid:
try:
    json.loads('{a: 1}', strict=False)
except json.JSONDecodeError as e:
    print(f"Unquoted key still fails: {e.msg}")

# But raw control characters are accepted:
result = json.loads('{"a": "x\ty"}', strict=False)
print(f"Control char accepted: {repr(result['a'])}")  # 'x\ty'

Practical pattern: try strict first, fall back to lenient

A robust strategy is to attempt parsing with strict=True (the default) first. If a JSONDecodeError is raised, retry with strict=False. This approach prioritizes strict compliance while providing a fallback mechanism for handling model quirks.

The first pass preserves full RFC validation, catching genuine syntax errors early. The second pass provides graceful degradation only for the specific case of raw control characters. For high-throughput pipelines, consider logging when the fallback triggers so you can detect upstream issues in prompt templates or post-processing code.

import json

raw = '{"message": "hello\tworld"}'

# Two-pass pattern: try strict first, fall back to lenient
try:
    result = json.loads(raw)
except json.JSONDecodeError:
    result = json.loads(raw, strict=False)

print(result)  # {'message': 'hello\tworld'}
print(repr(result['message']))  # 'hello\tworld'

Things to check

  • Python 3.5+ (JSONDecodeError attributes lineno and colno were added in 3.5)
  • Familiarity with json.loads and JSONDecoder API
  • Understanding that RFC 7159 requires control characters in strings to be escaped

The strict parameter only affects characters in the 0-31 code point range inside strings; it does not relax other JSON syntax rules such as unquoted keys or trailing commas. Setting strict=False does not fix invalid escape sequences like A which are not valid JSON escapes regardless of strict mode. This parameter is decoder-only; the encoder (json.dumps) always escapes control characters when ensure_ascii is True, independent of any strict setting. The two-pass fallback pattern adds latency proportional to the input size for every parse that fails the strict attempt; for high-throughput pipelines consider pre-sanitizing the model output instead.

Sources

  1. Python: json ↗
  2. JSON Schema: objects and required properties ↗
Back to top ↑