1

I have my JSON code below being stored in jso variable.

jso = {
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }

Whenever I'm trying to fetch the data or iterate over the JSON Object, it's printing the data in the reverse order i.e object first and then the other parameters.

For eg. I execute:

>>> for k,v in jso.iteritems():
...     print v
... 

AND THE OUTPUT I GOT:

OUTPUT GETTING

{'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986', 'GlossDef': {'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}, 'title': 'S'}

It can be seen that though 'title':'S' was written before the 'GlossList' Object still the data is printing in the reverse order. I mean it should have:

OUTPUT EXPECTED

{ 'title': 'S', 'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986', 'GlossDef': {'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}}
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
softvar
  • 17,917
  • 12
  • 55
  • 76

1 Answers1

4

Dictionaries in python are unordered collections:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

But, if you've loaded json from the string, you can load it directly to the OrderedDict, see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 2
    It's also important to note that this concept extends to JSON. "An object is an unordered set of name/value pairs." – Explosion Pills Sep 15 '13 at 21:28
  • Thanks @alecxe ! But I'm unable to use `isinstance(v,(list))` or `isinstance(v,(str))` for checking the entry being a list/string when I'm iterating over OrderDict for k,v in my_ordered_dict.iteritems(): ... print k,v GlossDiv OrderedDict([(u'title', u'S'), (u'GlossList', OrderedDict([(u'GlossEntry', OrderedDict([(u'Abbrev', u'ISO 8879:1986'), (u'GlossDef', OrderedDict([(u'GlossSeeAlso', [u'GML', u'XML'])])), (u'GlossSee', u'markup')]))]))]) >>>isinstance(v,(list)) #isinstance(v,(str)) – softvar Sep 15 '13 at 22:21
  • @VarunMalhotra This requirement is not in your question. Edit your question to explain what you need. – Graeme Stuart Sep 15 '13 at 22:27
  • @VarunMalhotra remember, that you have nested ordered dicts. `v` in `for k,v in my_ordered_dict.iteritems()` is an `OrderedDict` too. – alecxe Sep 15 '13 at 22:31