-
-
Save lsloan/eb365be1a7c47e2f8d492f031187cf43 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