Skip to content

Instantly share code, notes, and snippets.

@nanonyme
Created January 2, 2019 19:30
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 nanonyme/8df8b45367c40f40f31bc434f24ecc9a to your computer and use it in GitHub Desktop.
Save nanonyme/8df8b45367c40f40f31bc434f24ecc9a to your computer and use it in GitHub Desktop.
JSON to YAML conversion
from ruamel.yaml import YAML
import json
from pathlib import Path
import sys
from collections import OrderedDict
import collections
from ruamel.yaml.comments import CommentedMap
def convert(filename):
yaml = YAML()
yaml.default_flow_style = False
yaml.indent(mapping=2, sequence=4, offset=2)
original = Path(filename)
target = original.with_suffix(".yml")
with original.open("r") as f:
data = json.load(f, object_pairs_hook=lambda x: CommentedMap(OrderedDict(x)))
with target.open("w") as f:
yaml.dump(data, f)
if __name__ == "__main__":
convert(sys.argv[1])
@nanonyme
Copy link
Author

nanonyme commented Jan 2, 2019

The object_pairs_hook is only relevant for Python 3 older than 3.6 where dicts have undetermined order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment