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
476k127 gold badges1.1k silver badges1.2k bronze badges
asked Sep 15, 2013 at 21:22

1 Answer 1

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:

answered Sep 15, 2013 at 21:25
4
  • 2
    It's also important to note that this concept extends to JSON. "An object is an unordered set of name/value pairs." Commented Sep 15, 2013 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)) Commented Sep 15, 2013 at 22:21
  • @VarunMalhotra This requirement is not in your question. Edit your question to explain what you need. Commented Sep 15, 2013 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. Commented Sep 15, 2013 at 22:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.