Python

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

Leave a Reply