These gists record how to transform between yaml and json files, using script languages.
Last active
February 4, 2021 08:49
-
-
Save xiangaoole/f192adea2e588a2b9eaa6fc84766a235 to your computer and use it in GitHub Desktop.
yaml to json | json to yaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
# pip3 install pyyaml | |
import yaml | |
# print to screen | |
with open('example.json') as file: | |
o = json.load(file) | |
print(yaml.dump(o)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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