21

I've got a file that contains a JSON object. It's been loaded the following way:

with open('data.json', 'r') as input_file:
  input_data = input_file.read()

At this point input_data contains just a string, and now I proceed to parse it into JSON:

data_content = json.loads(input_data.decode('utf-8'))

data_content has the JSON representation of the string which is what I need, but for some reason not clear to me after json.loads it is altering the order original order of the keys, so for instance, if my file contained something like:

{ "z_id": 312312,
  "fname": "test",
  "program": "none",
  "org": null
}

After json.loads the order is altered to let's say something like:

{ "fname": "test",
  "program": None,
  "z_id": 312312,
  "org": "none"
}

Why is this happening? Is there a way to preserve the order? I'm using Python 2.7.

5
  • 3
    why do you need dictionary order? Commented May 4, 2017 at 17:39
  • 1
    If you really need order, then stackoverflow.com/questions/6921699/… Commented May 4, 2017 at 17:41
  • 1
    I believe this was a bad example because the keys are ordered alphabetically. I'll edit the example. My point is that I want the object not altered but to hold whatever order it had initially Commented May 4, 2017 at 17:43
  • If you need order, then use Python3.6: stackoverflow.com/q/39980323/7216865 Commented May 4, 2017 at 17:43
  • 1
    See also: stackoverflow.com/questions/6921699 Commented Sep 29, 2019 at 17:55

2 Answers 2

36

Dictionaries (objects) in python have no guaranteed order. So when parsed into a dict, the order is lost.

If the order is important for some reason, you can have json.loads use an OrderedDict instead, which is like a dict, but the order of keys is saved.

from collections import OrderedDict

data_content = json.loads(input_data.decode('utf-8'), object_pairs_hook=OrderedDict)
Sign up to request clarification or add additional context in comments.

1 Comment

3

This is not an issue with json.load. Dictionaries in Python are not order enforced, so you will get it out of order; generally speaking, it doesn't matter, because you access elements based on strings, like "id".

1 Comment

It does matter in this case since I gotta dump the data into an excel file and need preserve the structure. All my files will not have the same structure so cannot access each element individually

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.