Python doesn’t allow sorting of a dictionary. But while converting dictionary to a JSON, you can explicitly sort it so that the resulting JSON is sorted by keys. This is true for multi-dimentional dictionary. In case you need to sort a multi-dimentional JSON, convert it to dictionary and then dump it back to JSON with sorted flag.
ud = json.loads(js) print js # Unsorted JSON print ud # JSON to Dictionary (Unsorted) print json.dumps(ud, sort_keys=True) # This JSON will be sorted recursively
Advertisements
Thanks for the post, it’s really interesting, Python is wonderful for these things.
Few months ago I wrote a function in C# to achieve the same result, using the popular JSON.NET library.
1. in C# is painful, when you want to read an anonymous structure and sort it
2. many people gave up when they tried, some say that it’s not even possible to sort anonymous types (I read many comments in StackOverflow)