Reputation: 8855
I have a JSON that looks like the following (this example is just a toy example to illustrate the point, default iteration might work by luck).
{ "A": 1, "B": 2, "C": 3 }
I can load this JSON into a Python (v2.7) dictionary.
with open('/path/to/json/file') as f:
json_data = json.load(f)
I then iterate over the key-value pairs as follows.
for k, v in json_data.iteritems():
print('{}, {}'.format(k, v))
What is printed is the following.
A, 1 C, 3 B, 2
What I want is to be able to iterate over the items in the order that was specified in the JSON. So, my expected output should be.
A, 1 B, 2 C, 3
Is there any way to read in and store the key-value pairs from JSON to a Python dictionary such that when I iterate over them, the order specified by JSON is preserved and read back in such order?
I do not have control with the producer of the JSON to store the data in an array (discussed here for Java). I am wondering if there is a LinkedHashMap like in Java with Python that perhaps I may use with json.load
to preserve the insertion order for reading.
Any help is appreciated.
Upvotes: 0
Views: 247
Reputation: 1435
You can get the json loader to build an OrderedDict:
import json
import collections
with open('example.json') as f:
json_object = json.load(f,object_pairs_hook=collections.OrderedDict)
Upvotes: 4