Skip to content

Instantly share code, notes, and snippets.

@yuvipanda
Created April 11, 2014 16:14
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 yuvipanda/10481205 to your computer and use it in GitHub Desktop.
Save yuvipanda/10481205 to your computer and use it in GitHub Desktop.
Converts YAML files to JSON files while preserving order of dictionaries
#!/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)
@RoxanaTapia
Copy link

This will return a type OrderedDict, but data will not match the order in the input stream.

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