Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.