Skip to content
wordpiece.org

Inspecting tokenization of JSON payloads and escaping

Serialize the same object with different whitespace settings and compare exact BERT encodings; separate serialization differences from tokenizer differences

Published 8 min read Verified

JSON is a data model; a JSON payload is a byte sequence. BERT sees the byte sequence, not the model. Two serializations of the same object—compact versus default separators, or ensure_ascii=True versus False—can therefore produce different token IDs before the tokenizer is asked to do anything semantic. The diagnostic question is not “what does BERT think this JSON means”; it is “which serialization choices changed the token sequence, and which changes came from the tokenizer’s own fragmentation or unknown-token handling?”

A serialization diff that looks like a tokenizer diff

Start by pinning the tokenizer. For this article, the applicable encoder is google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594, loaded with transformers==4.56.2 and use_fast=True. The pinned vocabulary size is 30,522. The fast tokenizer reads the pinned tokenizer.json, which defines normalization and WordPiece behavior. If you use a different revision or a slow tokenizer, you are no longer making the same measurement.

The concrete problem is that json.dumps has independent knobs. separators=(",", ":") removes whitespace after commas and colons. The default separators keep a space after , and :. indent=2 adds newlines and indentation spaces. ensure_ascii=True escapes non-ASCII characters as \uXXXX. Each knob changes the string that reaches the tokenizer. BERT’s WordPiece algorithm then greedily matches subwords, falls back to [UNK] when a character cannot be formed, and emits special tokens like [CLS] and [SEP]. So a token-count difference between two serializations can be caused by serialization alone. A token-count difference between two tokenizer revisions can be caused by the tokenizer alone. You need offsets to tell them apart.

A small diagnostic you can run

The following script serializes one object four ways, encodes each variant with the pinned tokenizer, and prints token strings, IDs, character offsets, and the special-token mask. It then compares token ID sequences. It does not assume any particular output; run it to see what this revision produces.

import json
from transformers import AutoTokenizer

MODEL = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"

tokenizer = AutoTokenizer.from_pretrained(
    MODEL,
    revision=REVISION,
    use_fast=True,
)

payload = {
    "name": "café",
    "note": "line\nbreak",
    "quote": 'he said "hi"',
    "path": "C:\\tmp",
}

variants = {
    "compact_ascii": json.dumps(payload, separators=(",", ":"), ensure_ascii=True),
    "compact_raw": json.dumps(payload, separators=(",", ":"), ensure_ascii=False),
    "default_ascii": json.dumps(payload, ensure_ascii=True),
    "indent_raw": json.dumps(payload, indent=2, ensure_ascii=False),
}

encodings = {}
for label, text in variants.items():
    enc = tokenizer(
        text,
        add_special_tokens=True,
        return_offsets_mapping=True,
        return_special_tokens_mask=True,
    )
    encodings[label] = (text, enc)

for label, (text, enc) in encodings.items():
    print(f"\n--- {label} ---")
    print(f"serialized length: {len(text)}")
    print(f"input_ids length (model-input tokens): {len(enc['input_ids'])}")
    for tok, tid, off, special in zip(
        enc.tokens(),
        enc["input_ids"],
        enc["offset_mapping"],
        enc["special_tokens_mask"],
    ):
        print(f"{tok!r:>18} id={tid:<6} offsets={off} special={special}")

labels = list(variants)
base_ids = encodings[labels[0]][1]["input_ids"]
for label in labels[1:]:
    ids = encodings[label][1]["input_ids"]
    same = ids == base_ids
    print(f"\n{labels[0]} vs {label}: token ID sequences equal? {same}")
    if not same:
        min_len = min(len(base_ids), len(ids))
        first_diff = None
        for i in range(min_len):
            if base_ids[i] != ids[i]:
                first_diff = i
                break
        if first_diff is None:
            print(
                f"  sequences match for first {min_len} tokens; "
                f"lengths differ: {len(base_ids)} vs {len(ids)}"
            )
        else:
            print(
                f"  first difference at index {first_diff}: "
                f"{base_ids[first_diff]} != {ids[first_diff]}"
            )
            print(f"  base token: {encodings[labels[0]][1].tokens()[first_diff]!r}")
            print(f"  other token: {encodings[label][1].tokens()[first_diff]!r}")

Reading the output: content tokens vs model-input tokens

The input_ids length is the number of model-input tokens. That includes [CLS] and [SEP], and it includes every token produced from JSON punctuation, whitespace, and escaped content. When you compare payloads, do not treat that length as a semantic measure. Strip the special-token positions first. You can use special_tokens_mask to exclude them, then compare the remaining token IDs. That gives you the payload-bearing token sequence for this serialization and this tokenizer revision.

The offsets are the bridge back to serialization. A token’s offset is a (start, end) character pair in the exact string you passed to the tokenizer. If indent_raw has additional offsets covering newline and space characters, those are serialization tokens, not JSON content tokens. If compact_ascii turns café into caf\u00e9, the offsets for that value span more characters and often more tokens. You can see whether the extra tokens are fragments of the escape or a single [UNK] token.

Unknown tokens and fragmentation are different failure modes. An unknown token is a single token ID for [UNK]; the tokenizer could not form a known subword from the input span. Fragmentation is one input span producing multiple known subword tokens, such as a rare word split into WordPiece pieces. Escaping often causes fragmentation because it replaces one non-ASCII character with several ASCII characters. The diagnostic prints both the token strings and the offsets, so you can distinguish “this character is unknown” from “this character exploded into many pieces.”

Escaping choices and what they change

For the pinned English uncased model, ensure_ascii=True is a serialization choice with tokenizer consequences. It converts é to six characters: \, u, 0, 0, e, 9. The tokenizer then processes those characters using the pinned WordPiece vocabulary. With ensure_ascii=False, the same payload contains the actual é. Normalization in the pinned tokenizer.json may lowercase or strip accents before WordPiece, or the character may be outside the vocabulary. The script reveals which path occurs. Do not assume that the raw form always produces fewer tokens; run the comparison.

Whitespace is similar. Compact JSON removes spaces after separators. Default JSON keeps them. Indented JSON adds many whitespace characters. Each whitespace character is input to the tokenizer. WordPiece may treat whitespace as part of a token boundary or as a character that becomes [UNK]. Again, offsets show exactly which serialized characters became which tokens. The practical rule is: when comparing two JSON payloads for tokenization, hold serialization constant. If you cannot, compare after stripping special tokens and aligning offsets, and report both the serialization variant and the tokenizer revision.

Limitations and re-check procedure

Verified: 2026-10-05. The scope here is google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2 and use_fast=True; the pinned vocabulary size is 30,522. A limitation is that token behavior is revision-specific and language-specific. The English uncased model does not cover all scripts, and this diagnostic does not predict the behavior of other encoders or unrelated LLMs. If you switch to google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, the pinned vocabulary size is 119,547 and its normalization and vocabulary differ, so rerun the script rather than reusing counts.

To re-check when the pinned file or dependency changes, keep the full commit hash in from_pretrained and confirm it is still the revision you intend. Rerun the diagnostic on a fixed payload, compare offset_mapping and special_tokens_mask for the same serialization variants, and inspect the pinned tokenizer.json for normalization and vocabulary changes. If you upgrade transformers, rerun under the new version and record the version alongside the outputs. A change in token count is only meaningful when you can say which serialization string, which tokenizer revision, and which dependency version produced it.

Sources

Token counts in this article were produced by the tokenizers pinned on the sources page and are checked by the site's test suite. If a count ever stops matching the pinned vocabulary, the build fails.

Check it yourself

Open the tokenizer

Every count in this guide comes from a vocabulary pinned by checksum. Paste the same text into the tool and you will get the same output.

Related guides