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 stdin.

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.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #ruby #command-line #yaml #json.

This post was filed under articles.

Has this content helped you? Please consider supporting me so I can continue to create content like this!

This post is part of the series yaml-to-json.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.