0

I am trying to build a list with data of a JSON object. However the order of the list does not match the oder of the JSON object and changes nearly everytime I run the code.

{
    "project":{
        "Projektnamen":{
            "Server":{
                "Server1":{
                    ...
                },
                "Server2":{
                    ...
                },
                "Server3":{
                    ...
                }
            }
        }
    }
}
with open('json_data.json') as json_file:
    # json CONFIG_JSON Konfigurationsdatei
    CONFIG_JSON = json.load(json_file)

for key in CONFIG_JSON["project"]["Projektnamen"]["Server"]:
    servernamen.append(key)

Expected result: servernamen = [Server1, Server2, Server3]

However the order always changes. Last result: servernamen = [Server3, Server1, Server2]

  • 1
    probably before Python 3.6 array (or rather dictionary) doesn't have to keep order. If you need order then better keep it as list. – furas Jun 27 '19 at 06:37
  • 4
    dictionary does not guarantee order. – The Scientific Method Jun 27 '19 at 06:46
  • 1
    @TheScientificMethod That information is out of date. Please see https://stackoverflow.com/a/47881325/4014959 OTOH, the JSON specification doesn't require `{}` objects to retain order, so it's generally *not* wise to have a data flow that expects them to retain order. – PM 2Ring Jun 27 '19 at 08:07

2 Answers2

1

You can import your JSON data already sorted by using collections.OrderedDict and the arguments of json.load:

from collections import OrderedDict
import json


r = json.load(open('json_data.json'), object_pairs_hook=OrderedDict)
wencakisa
  • 5,850
  • 2
  • 15
  • 36
0

json.loads deserializes JSON into a dictionary object, which is a hash table that is not ordered.

You can use OrderedDict from collections to sort keys. Example

from collections import OrderedDict

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
new_d = OrderedDict(sorted(d.items()))

print(new_d)
# OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
schmutov
  • 207
  • 1
  • 2
  • 13