Skip to content

Instantly share code, notes, and snippets.

@tyronewilson
Forked from xiaohanyu/yaml_to_json.rb
Last active March 17, 2020 05:45
Show Gist options
  • Save tyronewilson/bfa56fca3b0d1720b127e4ea37fe7288 to your computer and use it in GitHub Desktop.
Save tyronewilson/bfa56fca3b0d1720b127e4ea37fe7288 to your computer and use it in GitHub Desktop.
convert yaml to json in ruby
#!/usr/bin/ruby
# Quick and easy way to convert from yaml to json with pretty format
# Usage:
# Example 1:
#
# # Explicitly give the output filename
# ./yaml_to_json.rb input_file/name.yaml outputfile/name.json
#
# Example 2:
#
# # Will implicitly use the input file name with .json extension
# ./yaml_to_json.rb inputfilename.yaml
#
# Example 3:
#
# # Also works for .yml extension
# ./yaml_to_json.rb inputfilename.yml
#
require 'json'
require 'yaml'
input_filename = ARGV[0]
output_filename = ARGV[1] || input_filename.gsub(/(yml|yaml)$/, 'json')
input = JSON.pretty_generate(YAML.load(File.read(input_filename)))
File.open(output_filename, 'w') do |out|
out.write input
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment