Kieran Hunt

JSON is (almost) truncation safe

✦ 2024-09-28

In YAML, you can’t detect if a document has been truncated.

my-favourite-things:
  - foo
  - bar

How do we know if the last n bytes of that document were cut off or not? What if qux was also one of my favourite things? What if bar should’ve been bar baz?

JSON is mostly safe from this. A few posts ago, I showed how a JSON document doesn’t have to start with an object. In this post, we’ll explore each type of JSON document and how how it fares with truncation.

This post is interactive
Use the range sliders to truncate each JSON document and see errors from the JSON parser.

object

{ "foo": "bar" }
✅ Valid JSON

An object’s trailing }, which closes a corresponding {, protects against truncation.

array

[ "foo", "bar" ]
✅ Valid JSON

The array’s trailing ], which closes a corresponding [, protects against truncation.

string

"foo bar baz"
✅ Valid JSON

Again, the unbalanced " will indicate truncation.

"true", "false", and "null"

true
✅ Valid JSON
false
✅ Valid JSON
null
✅ Valid JSON

These three behave in exactly the same way. They’re literals, so any missing characters will not parse.


number

1337
✅ Valid JSON
3.1415926535
✅ Valid JSON
2.998e8
✅ Valid JSON

🚨 JSON documents, where the document is just a number, are not truncation safe. 🚨


Using the sliders above you can see that, for various levels of truncation, it’s impossible to tell if the number has been truncated or not.