Skip to content

Instantly share code, notes, and snippets.

@evindunn
Last active June 25, 2021 22:35
Show Gist options
  • Save evindunn/ad1b6b5311c47484a89a8abf59b645b7 to your computer and use it in GitHub Desktop.
Save evindunn/ad1b6b5311c47484a89a8abf59b645b7 to your computer and use it in GitHub Desktop.
json2yaml.py
#!/usr/bin/env python3
# Uses PyYAML>=0.2.5
from yaml import dump as yaml_dump
from json import load as json_load, JSONDecodeError
from argparse import ArgumentParser
from os.path import exists as path_exists
from sys import exit, stderr
def main():
argparser = ArgumentParser(description="Convert a JSON file to YAML")
argparser.add_argument(
"json_file",
type=str,
help="The JSON file to convert"
)
args = argparser.parse_args()
json_file = args.json_file
if not path_exists(json_file):
print("'{}' not found".format(json_file), file=stderr)
return 1
with open(json_file) as f:
try:
as_dict = json_load(f)
except JSONDecodeError:
print("'{}' is not valid JSON".format(json_file), file=stderr)
return 1
print(yaml_dump(as_dict))
return 0
if __name__ == '__main__':
exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment