0

I have a json file which I'm reading as a json object and looping over the object. The json object is a list of dictionaries, which has the following structure.

[{
    "ACT": "235",
    "Unit": "ABG",
    "Center": "West",
    "web": "160",
    "Env": "QA",
    "Ret": "30",
    "Int": "2",
    "All": "BU",
    "SRV": "Std",
    "Type": "none"
}, {
    "ACT": "178",
    "Unit": "GHu",
    "Center": "West",
    "web": "198",
    "Env": "PE",
    "Ret": "30",
    "Int": "3",
    "All": "BU",
    "SRV": "Std",
    "Type": "none"
}, {
    "ACT": "167",
    "Unit": "orp",
    "Center": "East",
    "web": "190",
    "Env": "PD",
    "Ret": "30",
    "Int": "1",
    "All": "BU",
    "SRV": "Std",
    "Type": "none"
}]

Following is my code to loop over the json object

import json
import sys

ref_data = json.load(open('roche_test.json'))

json_len = len(ref_data)

i = 0
j = 0

for i in range(0,json_len):
    for j in range (0,len(ref_data[i])):
        print ref_data[i].values()[j]

It's looping through all dictionaries in order, however the looping over each dictionary is jumbled.

Eg : print ref_data[0].values()[3] will output 2 and print ref_data[0].keys()[3] will output Int whereas it should have been outputing 160 and web.

Any inputs on why this might be happening?

martineau
  • 119,623
  • 25
  • 170
  • 301
iprof0214
  • 701
  • 2
  • 6
  • 19
  • 3
    [JSON objects](http://www.json.org/) are unordered. So are Python `dict`s (they're ordered in newer CPython and PyPy, with some caveats, but that's obviously not relevant to you). So it makes perfect sense to parse JSON objects into Python dicts with arbitrary ordering. – abarnert Mar 28 '18 at 22:58
  • 1
    Check out top answer [here](https://stackoverflow.com/questions/30152688/json-dumps-messes-up-order) Sneha – Peter Dolan Mar 28 '18 at 22:59
  • Thanks Aran and Peter, will check them out and see if that helps. – iprof0214 Mar 28 '18 at 23:01
  • I'm not sure which question this is a dup of, because I'm not sure whether the OP (a) didn't know that JSON is defined as unordered, (b) does know that but wanted to get the in-file order anyway (for debugging purposes, or to work around a bug in some other code that assumes order, whatever) but didn't know that dicts are unordered, or (c) knows both and wanted to know how to use `OrderedDict` instead. – abarnert Mar 28 '18 at 23:02
  • Use of OrderedDict worked, thanks All. – iprof0214 Mar 29 '18 at 18:27

0 Answers0