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)

3 thoughts on “Convert JSON to YAML and back using python”

  1. 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)

Leave a Reply

Your email address will not be published. Required fields are marked *