Search code examples
pythondjangojsonsimplejson

simplejson returns values not in order


When working with simplejson in Django, I sometimes need to send the information strictly in order.

values = {"entry1":"value1","entry2":"value2","entry3":"value3"}
return HttpResponse(simplejson.dumps(values),content_type="application/json")

That's what it returns

{"entry2": "value2", "entry3": "value3", "entry1": "value1"}

But I want it to returns this instead:

{"entry1":"value1","entry2":"value2","entry3":"value3"}

How can I send the information in order in simplejson?


Solution

  • I sometimes need to send the information strictly in order.

    Don't use a dictionary then, use a list of tuples:

    values = [("entry1", "value1"), ("entry2", "value2"), ("entry3", "value3")]
    

    Dictionaries and JSON objects do not have a set order. Neither will preserve your input order, nor are they required to.

    To quote the JSON RFC:

    An object is an unordered collection of zero or more name/value pairs [...]

    and the Python dict.items() documentation:

    Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.