Created
August 8, 2014 15:05
-
-
Save Racum/7c40e0393c195bc97c41 to your computer and use it in GitHub Desktop.
Guaranteed-order JSON dump in Python using collections.OrderedDict.
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
import json | |
from collections import OrderedDict | |
def serialize_with(collection_type): | |
complex_object = collection_type() | |
complex_object['z'] = collection_type() | |
complex_object['z']['c'] = 30 | |
complex_object['z']['b'] = 20 | |
complex_object['z']['a'] = 10 | |
complex_object['y'] = '123' | |
complex_object['x'] = [] | |
complex_object['x'].append(collection_type([ | |
('c', 30), | |
('b', 20), | |
('a', 10), | |
])) | |
complex_object['x'].append(collection_type([ | |
('c', 300), | |
('b', 200), | |
('a', 100), | |
])) | |
return complex_object | |
print json.dumps(serialize_with(dict), indent=4) | |
# Output: | |
# { | |
# "y": "123", | |
# "x": [ | |
# { | |
# "a": 10, | |
# "c": 30, | |
# "b": 20 | |
# }, | |
# { | |
# "a": 100, | |
# "c": 300, | |
# "b": 200 | |
# } | |
# ], | |
# "z": { | |
# "a": 10, | |
# "c": 30, | |
# "b": 20 | |
# } | |
# } | |
print json.dumps(serialize_with(OrderedDict), indent=4) | |
# Output: | |
# { | |
# "z": { | |
# "c": 30, | |
# "b": 20, | |
# "a": 10 | |
# }, | |
# "y": "123", | |
# "x": [ | |
# { | |
# "c": 30, | |
# "b": 20, | |
# "a": 10 | |
# }, | |
# { | |
# "c": 300, | |
# "b": 200, | |
# "a": 100 | |
# } | |
# ] | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment