Skip to content

Instantly share code, notes, and snippets.

@jbrzozoski
Last active January 12, 2024 20:43
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 jbrzozoski/9a12a5b25293cc2be7f09cfa33e6a46e to your computer and use it in GitHub Desktop.
Save jbrzozoski/9a12a5b25293cc2be7f09cfa33e6a46e to your computer and use it in GitHub Desktop.
Minimal JSON-to-YAML converter with smarter multi-line handling
#!/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