0

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.

Jane Wayne
  • 8,205
  • 17
  • 75
  • 120
  • 3
    In all likelihood, the order that you received the key/value pairs in JSON is arbitrarily ordered, so why would you need to maintain order as a consumer? If the API thought order was important, they would have used a list structure – roganjosh Sep 21 '18 at 18:57
  • No, the key-value pairs are not arbitrarily ordered; that was definitely an oversight on their end. Yes, I agree, they should have used a list structure. – Jane Wayne Sep 21 '18 at 19:02
  • @JaneWayne Do you have to use Python 2.7? – G_M Sep 21 '18 at 19:03
  • @G_M Yes, for now; but our code is branched for 3.6 compatibility too; and so any logic would have to work for both 2.7 and 3.6. But I'd love to hear the solution that is dependent on 2.7. – Jane Wayne Sep 21 '18 at 19:04
  • @JaneWayne My first thought was that dictionaries are now ordered by default in Python 3.6 so you might not need any modifications there (would need to be tested). https://stackoverflow.com/a/39980744/8079103 – G_M Sep 21 '18 at 19:06
  • @G_M Guaranteed ordering is an implementation detail of CPython in 3.6; the language only provides the guarantee in 3.7. – chepner Sep 21 '18 at 19:34
  • The link can be correct without your summary of it being correct. – chepner Sep 21 '18 at 19:39

1 Answers1

4

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)
T Burgis
  • 1,395
  • 7
  • 9
  • You need to use `object_pairs_hook`, not `object_hook` (which is called on the `dict` created by the initial parsing). – chepner Sep 21 '18 at 19:27