Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
YAML to JSON - one-liner with Ruby
# Single line of Ruby <3.
ruby -rjson -ryaml -e "puts YAML.load_file('my_file.yml').to_json"
# You can also pipe it to Python to get pretty ouput
ruby -rjson -ryaml -e "puts YAML.load_file('my_file.yml').to_json" | \
python -mjson.tool
# Thats all. :)
Copy link

jonmoter commented Apr 1, 2018

Or if you want pretty-printed JSON without python:

ruby -rjson -ryaml -e "puts JSON.pretty_generate(YAML.load_file('my_file.yml'))"

Copy link

andrewpsp commented May 21, 2018

I'd like to load all yml from a relative path to json:
possibly : ruby -rjson -ryaml -e "puts YAML.load_file(File.dir(FILE).(all_yaml_files_in_directory.yaml').to_json"

Copy link

FilBot3 commented Jul 12, 2018

This works, however, unlike the python -m json.tool, the Ruby version doesn't sort the JSON. I'm doing this from inside vim too. So this is how I'm doing it to get it sorted, then re-spaced to 2 spaces.

:%!python -m json.tool
:%!ruby -rjson -e "puts JSON.pretty_generate(JSON.parse(" %

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment