Zellio.io

Convert JSON to YAML for a config file

2 min readLast updated 2 steps · runs on this page

Configuration tends to be authored in one format and required in another. This recipe validates a JSON document and rewrites it as YAML with two-space indentation, which is the form most deployment and CI systems read.

The steps

  1. 1

    Validate JSONvia Code Formatter

    A config with a trailing comma or a comment is not JSON, and the error position points at it.

  2. 2

    JSON → YAMLvia Code Formatter

    Objects become mappings, arrays become dash lists, strings are quoted only where YAML would otherwise misread them.

Ctrl+Enter runs · nothing leaves this tab

How the conversion treats values

Numbers, booleans and null carry across as YAML scalars. Strings that YAML would interpret as something else are quoted: "yes", "no", "on", a version like 1.10, an octal-looking 0755, and anything starting with a character YAML treats as syntax. Everything else is left bare, which keeps the file readable.

Key order is preserved. YAML has no opinion about order, but people do, and a config file whose keys jump around between edits is harder to review.

When to convert rather than rewrite

When the JSON is generated: a tool emitted it, a service returned it, or it came out of a database. Converting keeps every value exact, which typing by hand does not. When a document is small and human-written, a rewrite is fine, but the conversion is still a useful check that the two say the same thing.

  • A Helm values file drafted as JSON in a script.
  • A GitHub Actions matrix built by hand in JSON, needed in the workflow file.
  • An OpenAPI document kept in JSON that a reviewer prefers to read as YAML.

Things YAML cannot express the same way

Duplicate keys in the JSON are an error here rather than a silent overwrite. Very long strings are emitted on one line; if you want folded blocks, fold them by hand afterwards. Keys that are not plain words are quoted, which is correct YAML but sometimes surprising.

Questions

Does it support anchors or comments?
No. JSON has neither, so there is nothing to convert. Add comments in the YAML after conversion; they survive a later hand edit but not a round trip back to JSON.
Why is a string like "1.10" quoted?
Because unquoted, YAML reads it as the number 1.1. Quoting keeps it as the text you had.