Convert YAML to JSON and Vice-Versa in Python: A How-To Guide

Effortlessly convert data between YAML and JSON formats in Python. Step-by-step guide with code examples for data interchange.
E
Edtoks1:43 min read

Converting Yaml to Json (vice-versa) is common in tech world.

Here is simple python code to convertion. Copy below code to converter.py

It uses two python modules yaml and json. You need to install Python yaml module before proceeding. Json is librarry availablle with default Python.

pip install pyyaml

#!/usr/bin/python3

import json,yaml,sys,os
import re

if len(sys.argv) != 2:
    print('Usage:\n  '+os.path.basename(__file__)+' /path/file{.json|.yml}')
    sys.exit(0)

path = sys.argv[1]

if not os.path.isfile(path):
    print('Bad or non-existant file: '+path)
    sys.exit(1)

def yamlToJson(source, dest):
    yamlFile = open(source)
    jsonFile = open(dest, 'w')
    jsonFile.write(json.dumps(yaml.load(yamlFile, Loader=yaml.SafeLoader), indent=4))
    print(f'Converted {source} to {dest}')

def jsonToYaml(source, dest):
    jsonFile = open(source)
    yamlFile = open(dest, 'w')
    yamlFile.write(yaml.dump(json.load(jsonFile)))
    print(f'Converted {source} to {dest}')

if __name__ == "__main__":

  if path.lower().endswith('json'):
    yamlFileName = re.sub('json$', 'yaml', path)
    #print('Yaml file name is: %s' %(yamlFileName))
    jsonToYaml(path, yamlFileName)
  elif path.lower().endswith('yaml'):
    jsonFileName = re.sub('yaml$', 'json', path)
    #print('JSON file name is: %s' %(jsonFileName))
    yamlToJson(path, jsonFileName)
  elif path.lower().endswith('yml'):
    jsonFileName = re.sub('yml$', 'json', path)
    #print('JSON file name is: %s' %(jsonFileName))
    yamlToJson(path, jsonFileName)
  else:
    print('Bad file extension. Must be yml, yml or json')

Here you can pass either yaml or json file. This pythin code convert the same to the another format, means if input is yaml then output is json file with same name.

Now execute as shown below

python3 converter.py test.json 

Output is 

Converted test.json to test.yaml

Similarly 

python3 converter.py test.yaml 

Output is 

Converted test.yaml to test.json

You caopy code and change as per your requirement.

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.