Created
January 2, 2019 19:30
-
-
Save nanonyme/8df8b45367c40f40f31bc434f24ecc9a to your computer and use it in GitHub Desktop.
JSON to YAML conversion
This file contains hidden or 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
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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The object_pairs_hook is only relevant for Python 3 older than 3.6 where dicts have undetermined order.