Convert JSON to YAML and back using python
Just a few lines of code to convert json to yaml and back.
Convert JSON to YAML
import json
import yaml
in_file = sys.argv[1]
out_file = sys.argv[2]
with open(in_file, 'r') as json_in, open(out_file, "w") as yaml_out:
json_payload = json.load(json_in)
yaml.dump(json_payload,sort_keys=False)
Convert YAML to JSON
import yaml
import json
in_file = sys.argv[1]
out_file = sys.argv[2]
with open(in_file, 'r') as yaml_in, open(out_file, "w") as json_out:
yaml_playload = yaml.safe_load(yaml_in)
json.dump(yaml_object, json_out)
5 Comments
Simon
Hi. You can use a free online tool to convert JSON to YAML https://freetools.site/data-converters/json-to-yaml
slommi
Hi Simon, I wanted to provide a solution without releasing data to third paties.
Robert Refer
Thank you for these snippets. I think the output file (“yaml_out”) was left out of the yaml.dump function arguments. It maybe should be: yaml.dump(json_payload, yaml_out, sort_keys=False)
nicholo
LIFESAVER
slommi
Hi Robert,
I wanted to demonstrate a conversion, and decided to output to stdout. Maybe a statement like:
print(yaml.dump(json_payload,sort_keys=False))
would be more pythonic. Writing to a file would need these lines.
with open(‘UserDetails.yaml’, ‘w’) as f:
data = yaml.dump(json_payload, f, sort_keys=False)
Thank you for your comment.