In addition to dumping the ordered list of keys alongside the dictionary, another low-tech solution, which has the advantage of being explicit, is to dump the (ordered) list of key-value pairs ordered_dict.items()
; loading is a simple OrderedDict(<list of key-value pairs>)
. This handles an ordered dictionary despite the fact that JSON does not have this concept (JSON dictionaries have no order).
It is indeed nice to take advantage of the fact that json
dumps the OrderedDict in the correct order. However, it is in general unnecessarily heavy and not necessarily meaningful to have to read all JSON dictionaries as an OrderedDict (through the object_pairs_hook
argument), so an explicit conversion of only the dictionaries that must be ordered makes sense too.