Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python json.loads changes the order of the object

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.

like image 385
Sebastian Avatar asked May 04 '17 17:05

Sebastian


People also ask

Does JSON loads preserve order?

This module's encoders and decoders preserve input and output order by default.

Does JSON dump change order?

Sort Keys JSON usually doesn't care about the order of the items. Therefore, when we dump a Python dictionary to a JSON string, the order of the items will be kept as-is. However, if we do want to sort the converted JSON string by the item keys, we can easily set sort_keys parameter to True .

What does JSON loads do in Python?

The json. load() is used to read the JSON document from file and The json. loads() is used to convert the JSON String document into the Python dictionary. fp file pointer used to read a text file, binary file or a JSON file that contains a JSON document.

Do JSON objects have order?

The JSON Data Interchange Standard definition at json.org specifies that “An object is an unordered [emphasis mine] set of name/value pairs”, whereas an array is an “ordered collection of values”. In other words, by definition the order of the key/value pairs within JSON objects simply does not, and should not, matter.


2 Answers

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)
like image 63
Rocket Hazmat Avatar answered Sep 23 '22 01:09

Rocket Hazmat


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".

like image 29
Neil Avatar answered Sep 23 '22 01:09

Neil