Created
April 11, 2014 16:14
-
-
Save yuvipanda/10481205 to your computer and use it in GitHub Desktop.
Converts YAML files to JSON files while preserving order of dictionaries
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 python | |
# Simple script that converts yaml files into json files while | |
# also preserving the order of any dictionary structures | |
# used in the yaml file | |
import sys | |
import yaml | |
import collections | |
import json | |
# Setup support for ordered dicts so we do not lose ordering | |
# when importing from YAML | |
_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG | |
def dict_representer(dumper, data): | |
return dumper.represent_mapping(_mapping_tag, data.iteritems()) | |
def dict_constructor(loader, node): | |
return collections.OrderedDict(loader.construct_pairs(node)) | |
yaml.add_representer(collections.OrderedDict, dict_representer) | |
yaml.add_constructor(_mapping_tag, dict_constructor) | |
data = yaml.load(open(sys.argv[1])) | |
print json.dumps(data, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will return a type OrderedDict, but data will not match the order in the input stream.