Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xiangaoole
Last active February 4, 2021 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiangaoole/f192adea2e588a2b9eaa6fc84766a235 to your computer and use it in GitHub Desktop.
Save xiangaoole/f192adea2e588a2b9eaa6fc84766a235 to your computer and use it in GitHub Desktop.
yaml to json | json to yaml

These gists record how to transform between yaml and json files, using script languages.

import json
# pip3 install pyyaml
import yaml
# print to screen
with open('example.json') as file:
o = json.load(file)
print(yaml.dump(o))
require 'json'
require 'yaml'
# print to screen
puts JSON.load('some.json').to_yaml
# or oneline shell:
# ruby -ryaml -rjson -e "puts JSON.load('some.json').to_yaml"
# write to file
=begin
thing = JSON.load('some.json')
File.open('some.yaml', 'w') do |f|
f.write(thing.to_yaml)
end
=end
import json
# pip3 install pyyaml
import yaml
# print to screen
with open('example.yaml') as file:
o = yaml.load(file, Loader=yaml.FullLoader)
print(json.dumps(o, indent=2))
# yaml to json
require 'yaml'
require 'json'
# print to screen
puts JSON.pretty_generate(YAML.load_file('some.yml'))
# or oneline shell:
# ruby -ryaml -rjson -e "puts JSON.pretty_generate(YAML.load_file('some.yml'))"
# write to file
=begin
thing = YAML.load_file('some.yml')
File.open('some.json', 'w') do |f|
f.write(JSON.pretty_generate(thing))
end
=end
# convert all yaml files of a directory
=begin
Dir.glob('dir/*.yml') do |yml_name|
json_name = yml_name.sub(/\.[^.]+\z/, ".json")
File.open(json_name, 'w') do |f|
f.write(JSON.pretty_generate(YAML.load_file(yml_name)))
end
end
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment