Converting YAML to JSON and vice versa (Part 1 - Ruby)
I've recently been finding myself trying to coerce YAML to JSON and vice versa quite a bit, partly to convert attributes from a Test Kitchen YAML file to a nice JSON object that can be consumed by Vagrant's Chef provisioner.
As it's been required a number of times, I decided that I needed to script it. The key requirement I have for scripting it is that the script follows the UNIX Philosophy - more specifically the second point,
Expect the output of every program to become the input to another, as yet unknown, program.. This means that I can easily create Bash pipelines, i.e. in conjunction with Python's JSON module:
ytoj < file.yml | python -m json.tool.
Converting from YAML to JSON
To convert from YAML to JSON, we can use the following:
#!/usr/bin/env ruby require 'yaml' require 'json' puts(YAML.load(ARGF.read).to_json)
This takes advantage of
ARGF, which is a file descriptor that points to
Using inspiration from otobrglez's gist, we can shorten this down to the following oneliner:
ruby -ryaml -rjson -e 'puts(YAML.load(ARGF.read).to_json)'
Converting from JSON to YAML
To convert from JSON to YAML, we can use the following:
#!/usr/bin/env ruby require 'yaml' require 'json' puts(JSON.load(ARGF.read).to_yaml)
Again, we can shorten this down to the following oneliner:
ruby -ryaml -e 'puts(YAML.load(ARGF.read).to_yaml)'
Thanks to Jack Gough for a tip on reducing the above - due to JSON being parseable as YAML, we can reduce dependency on the JSON library.