DEV Community

Five values that silently change meaning when JSON becomes YAML

Disclosure: I build ToolPlank, a set of free browser tools that includes a JSON to YAML converter. I ran every example below through it.

YAML looks simple until a value that was a plain string in JSON gets read as something else. The cause is almost always YAML 1.1, which many tools still use (Kubernetes manifests, Docker Compose, Ansible and a lot of older parsers). YAML 1.2 fixed most of this, but you rarely control which parser reads your file.

Here is a small JSON object with several traps in it:

{ "country": "no", "answer": "yes", "flag": "off", "time": "1:30", "mode": "0755", "tilde": "~", "nothing": null, "word": "null" }

yes, no, on, off are booleans in YAML 1.1

A YAML 1.1 parser reads country: no as false, not the string "no". This is the famous Norway problem: the country code NO becomes false. The same happens to yes, on, off, y and n in several parsers.

1:30 can become 90

YAML 1.1 has base-60 numbers, so time: 1:30 can load as the integer 90 (1 x 60 + 30). Port mappings like 80:80 have hit the same trap.

Leading zeros mean octal

mode: 0755 is read as octal in YAML 1.1, so you get the integer 493. File permissions are the usual victim.

A lone ~ is null

tilde: ~ loads as null, so the string "~" needs quotes.

null versus "null"

JSON null should stay null, but the text "null" must keep its quotes or it silently becomes a real null.

What a converter should do

With the default settings, the converter I built follows YAML 1.2 and leaves no, yes, off and 1:30 unquoted, because a 1.2 parser reads them as plain text. It quotes only what even 1.2 would misread:

country: no
answer: yes
flag: off
time: 1:30
mode: "0755"
tilde: "~"
nothing: null
word: "null"

If the file will be read by a 1.1 parser, switch the Compatibility option to "Also safe for YAML 1.1". The same input then comes out as:

country: "no"
answer: "yes"
flag: "off"
time: "1:30"
mode: "0755"
tilde: "~"
nothing: null
word: "null"

Quoted strings are safe in every YAML version, so when in doubt, quote.

If you want to try your own JSON, the converter is here: https://toolplank.com/tools/json-to-yaml/ . It runs in the browser and nothing you paste is uploaded.

What is the worst YAML surprise you have hit? I would like to add more cases to the converter's warnings.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.