Skip to content
Advertisement

How to get sorted list inside a dictionary with json.dumps()

I have the following problem: having a python dictionary like the following:

JavaScript

I would like to obtain an ordered json object such as:

JavaScript

At the moment I use the following:

JavaScript

But the two list inside my object are not sorted, and I get:

JavaScript

probably because the custom JSONEncoder skips a type that already knows how to manage (list).

UPDATE

Martijn solution below works perfectly for the example above, but unfortunately I have to manage more complicated dictionaries, with a bigger depth: for example the following two

JavaScript

They would be the same if the lists inside the same would be sorted. But they aren’t with the class above, and I get 2 different json strings:

JavaScript

Any idea to fix this?

Advertisement

Answer

default isn’t called for lists; that method is only for types the encoder doesn’t know how to handle. Override the encode method instead:

JavaScript

This essentially just sorts all lists (recursively) before encoding; this could have been done before passing it to json.dumps() but this way it is part of the responsibility of the encoder, just like sorting the keys is.

Demo:

JavaScript
Advertisement