Skip to content

Instantly share code, notes, and snippets.

@otobrglez
Created June 3, 2016 13:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save otobrglez/66274639697f377de8ec8047a248b8f0 to your computer and use it in GitHub Desktop.
Save otobrglez/66274639697f377de8ec8047a248b8f0 to your computer and use it in GitHub Desktop.
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. :)
@jonmoter
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'))"

@andrewpsp
Copy link

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"

@FilBot3
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(ARGF.read))" %

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