Skip to content

Instantly share code, notes, and snippets.

@onyxfish
Created May 29, 2014 17:25
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save onyxfish/69e1eaf1fa43503e4be1 to your computer and use it in GitHub Desktop.
Save onyxfish/69e1eaf1fa43503e4be1 to your computer and use it in GitHub Desktop.
Usage of object_pairs_hook to load JSON with guaranteed key order
#!/usr/bin/env python
from collections import OrderedDict
import json
write_data = OrderedDict([
('a', '1'),
('b', '2'),
('c', '3')
])
print 'It\'s a dict!'
print write_data
print ''
with open('test.json', 'w') as f:
json.dump(write_data, f)
with open('test.json') as f:
read_data = json.load(f)
print 'Order is not guaranteed:'
print read_data
print ''
with open('test.json') as f:
read_data = json.load(f, object_pairs_hook=OrderedDict)
print 'Order *is* guaranteed:'
print read_data
@achi11es
Copy link

OrderedDict isn't working on Python 3.5.2
" from UserDict import DictMixin
ImportError: No module named 'UserDict' "

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