Created
May 29, 2014 17:25
-
-
Save onyxfish/69e1eaf1fa43503e4be1 to your computer and use it in GitHub Desktop.
Usage of object_pairs_hook to load JSON with guaranteed key order
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 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OrderedDict isn't working on Python 3.5.2
" from UserDict import DictMixin
ImportError: No module named 'UserDict' "