Skip to content

Instantly share code, notes, and snippets.

@Racum
Created August 8, 2014 15:05
Show Gist options
  • Save Racum/7c40e0393c195bc97c41 to your computer and use it in GitHub Desktop.
Save Racum/7c40e0393c195bc97c41 to your computer and use it in GitHub Desktop.
Guaranteed-order JSON dump in Python using collections.OrderedDict.
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