Python – Sorting JSON by Keys

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

One thought on “Python – Sorting JSON by Keys

  1. 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)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s