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'}}}

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:

Sign up to request clarification or add additional context in comments.

4 Comments

It's also important to note that this concept extends to JSON. "An object is an unordered set of name/value pairs."
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))
@VarunMalhotra This requirement is not in your question. Edit your question to explain what you need.
@VarunMalhotra remember, that you have nested ordered dicts. v in for k,v in my_ordered_dict.iteritems() is an OrderedDict too.

Your Answer

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.