Skip to content

Instantly share code, notes, and snippets.

@lsloan
Forked from onyxfish/ordered_json.py
Created June 8, 2016 20:37
Show Gist options
  • Save lsloan/eb365be1a7c47e2f8d492f031187cf43 to your computer and use it in GitHub Desktop.
Save lsloan/eb365be1a7c47e2f8d492f031187cf43 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment