Skip to content

Instantly share code, notes, and snippets.

@oscarkramer
Last active July 31, 2018 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarkramer/9f12cf76521beec703712b24c9d89349 to your computer and use it in GitHub Desktop.
Save oscarkramer/9f12cf76521beec703712b24c9d89349 to your computer and use it in GitHub Desktop.
YAML to JSON File converter in python
# Converts input YAML file to JSON and writes the JSON to same filename but with ".json" ext.
import os, json, sys, yaml
if len(sys.argv) < 2:
print("Usage: "+sys.argv[0]+" <input.yaml>")
exit
try:
yamlFname = sys.argv[1]
pre, ext = os.path.splitext(yamlFname)
jsonFname = pre + ".json"
print("Converting "+yamlFname+" to "+jsonFname)
with open(yamlFname, 'r') as yamlStream:
data = yaml.safe_load(yamlStream)
jsonData = json.dumps(data, indent=3, sort_keys=True)
print(jsonData)
jsonStream = open(jsonFname,"w+")
jsonStream.write(jsonData);
jsonStream.close()
except yaml.YAMLError as exc:
print ("Error while parsing YAML file:")
if hasattr(exc, 'problem_mark'):
if exc.context != None:
print (' parser says\n' + str(exc.problem_mark) + '\n ' +
str(exc.problem) + ' ' + str(exc.context) +
'\nCorrect YAML and retry.')
else:
print (' parser says\n' + str(exc.problem_mark) + '\n ' +
str(exc.problem) + '\nCorrect YAML and retry.')
else:
print ("Something went wrong while parsing yaml file. Sorry it didn't work out.")
exit
21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment