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
An object’s trailing }
, which closes a corresponding {
, protects against truncation.
array
The array’s trailing ]
, which closes a corresponding [
, protects against truncation.
string
Again, the unbalanced "
will indicate truncation.
"true"
, "false"
, and "null"
These three behave in exactly the same way. They’re literals, so any missing characters will not parse.
number
🚨 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.