Last active
July 31, 2018 14:46
-
-
Save oscarkramer/9f12cf76521beec703712b24c9d89349 to your computer and use it in GitHub Desktop.
YAML to JSON File converter in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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