JSON / byte-count guide

Measure JSON document and wire-string bytes separately

A parsed JSON document and the serialized string sent to an API can have different byte counts. Compare an API limit with the exact UTF-8 wire representation, including escapes and formatting.

Judge limits from the wire representation

FixtureCharactersUTF-8 bytesLimit input
unicode2939Serialized string
escaped5454Serialized string
ascii2929Serialized string

Compare the API limit with the exact string sent, including escaping and formatting.

Reproduce the count locally

unicode.json contains Japanese text, escaped.txt is a serialized string with \u escapes, and ascii.json is ASCII. The byte values in expected.csv exclude the line ending and use UTF-8.

const bytes = new TextEncoder().encode(serialized).length;
+// compare bytes with the API limit

The same character count can use more UTF-8 bytes for non-ASCII text. Escapes can also make the string longer.

Verify before sending to an API

  1. Freeze the exact serialized string sent to the API.
  2. Measure its UTF-8 bytes and compare expected.csv.
  3. Record the API limit, headroom, newline and escape rules.
  4. Give the recipient checklist.md and the byte-count basis.

This guide is static browser-local material. JSON and input are not sent to an external server.

Do not claim fit from characters alone

Non-ASCII text, escapes, whitespace, newlines and serializer settings can change the byte count. Measure the actual wire string before deciding that it fits an API limit.