Skip to main content
CuteJSON
↑↓ Navigate Enter Select Esc Close

How to convert JSON to YAML without the classic 01234 bug

Published 2 min read By Akash Kinkar Pandey

YAML is a much larger language than JSON. Every JSON document is valid YAML, but the reverse is not true, which means a JSON to YAML converter can be fully correct while a YAML to JSON converter has to refuse the parts of YAML that JSON has no way to express.

Using the JSON to YAML converter

Choose a direction and an indent width, then press Convert. Writing to YAML, a mapping becomes one key per line, an array repeats its dash per item, and a null becomes a key with no value at all.

The bug this tool specifically guards against

A plain YAML scalar that looks like a number, a boolean, or a YAML indicator gets misread as that type the moment something parses the file back. A postcode of 01234 is the classic case: written unquoted, a YAML parser reads it as the number 1234 and the leading zero is gone for good. The same problem hits a string that happens to read "true" or "null".

Converting

{"zip":"01234","active":"true","note":null,"id":12345678901234567890}

produces:

zip: '01234'
active: 'true'
note: null
id: 12345678901234567890

Both string values are quoted specifically because leaving them bare would change their type on the way back. The actual null is written bare, since that is the correct unquoted spelling. The twenty digit id survives intact, because this goes through the token stream rather than a value parsed by JSON.parse.

What the reader accepts and what it refuses

Reading YAML back into JSON, the tool understands a mapping, a sequence, a quoted string, a block scalar, a flow collection, and a folded plain scalar. It refuses anchors, aliases and tags by name rather than silently ignoring them, because YAML has no equivalent for aliasing a value inside JSON and pretending otherwise would produce a document that only looks correct.

Round tripping

Converting the example above back from YAML returns the exact original document: "01234" and "true" as strings, null as null, and the full twenty digit integer. That round trip is the actual test of whether a converter’s quoting rules are right, since a wrong rule usually only shows up once you convert back and compare.

Back to all posts