Last active
January 12, 2024 20:43
-
-
Save jbrzozoski/9a12a5b25293cc2be7f09cfa33e6a46e to your computer and use it in GitHub Desktop.
Minimal JSON-to-YAML converter with smarter multi-line handling
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
#!/usr/bin/env python3 | |
""" | |
Convert a JSON file to a YAML file | |
""" | |
import sys | |
import json | |
import ruamel.yaml as yaml | |
def str_presenter(dumper, data): | |
if '\n' in data or '\t' in data: # check for complex or multiline strings | |
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') | |
return dumper.represent_scalar('tag:yaml.org,2002:str', data) | |
yaml.add_representer(str, str_presenter) | |
with open(sys.argv[1]) as f: | |
view = json.load(f) | |
if len(sys.argv) > 2: | |
if (sys.argv[2] == '+') and sys.argv[1].endswith('.json'): | |
outname = sys.argv[1][:-5] + '.yml' | |
else: | |
outname = sys.argv[2] | |
with open(outname, "w") as fout: | |
yaml.dump(view, fout) | |
else: | |
yaml.dump(view, sys.stdout) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment