16
votes

Is there any way in Python 2.6 to supply a custom key or cmp function to JSON's sort_keys?

I've got a list of dicts coming from JSON like so:

[
  {
    "key": "numberpuzzles1",
    "url": "number-puzzle-i.html",
    "title": "Number Puzzle I",
    "category": "nestedloops",
    "points": "60",
    "n": "087"
  },
  {
     "key": "gettingindividualdigits",
     "url": "getting-individual-digits.html",
     "title": "Getting Individual Digits",
     "category": "nestedloops",
     "points": "80",
     "n": "088"
  }
]

...which I've stored into the list variable assigndb. I'd like to be able to load in the JSON, modify it, and serialized it back out with dumps (or whatever), keeping the orders of the keys intact.

So far, I've tried something like this:

ordering = {'key': 0, 'url': 1, 'title': 2, 'category': 3,
             'flags': 4, 'points': 5, 'n': 6}

def key_func(k):
    return ordering[k]

# renumber assignments sequentially
for (i, a) in enumerate(assigndb):
    a["n"] = "%03d" % (i+1)

s = json.dumps(assigndb, indent=2, sort_keys=True, key=key_func)

...but of course dumps doesn't support a custom key like list.sort() does. Something with a custom JSONEncoder maybe? I can't seem to get it going.

5

5 Answers

4
votes

This is kind of ugly, but in case tokland's solution does not work for you:

data = [{'category': 'nestedloops', 'title': 'Number Puzzle I', 'url': 'number-puzzle-i.html', 'n': '087', 'points': '60', 'key': 'numberpuzzles1'}, {'category': 'nestedloops', 'title': 'Getting Individual Digits', 'url': 'getting-individual-digits.html', 'n': '088', 'points': '80', 'key': 'gettingindividualdigits'}]
ordering = {'key': 0, 'url': 1, 'title': 2, 'category': 3,
            'flags': 4, 'points': 5, 'n': 6}
outlist = []
for d in data:
    outlist.append([])
    for k in sorted(d.keys(), key=lambda k: ordering[k]):
        outlist[-1].append(json.dumps({k: d[k]}))

for i, l in enumerate(outlist):
    outlist[i] = "{" + ",".join((s[1:-1] for s in outlist[i])) + "}"

s = "[" + ",".join(outlist) + "]"
12
votes

An idea (tested with 2.7):

import json
import collections
json.encoder.c_make_encoder = None
d = collections.OrderedDict([("b", 2), ("a", 1)])
json.dumps(d)
# '{"b": 2, "a": 1}'

See: OrderedDict + issue6105. The c_make_encoder hack seems only to be needed for Python 2.x. Not a direct solution because you have to change dicts for OrderedDicts, but it may be still usable. I checked the json library (encode.py) and the ordered is hardcoded:

if _sort_keys:
    items = sorted(dct.items(), key=lambda kv: kv[0])
0
votes

I had the same problem and collections.OrderedDict was just not fit for the task because it ordered everything alphabetically. So I wrote something similar to Andrew Clark's solution:

def json_dumps_sorted(data, **kwargs):
    sorted_keys = kwargs.get('sorted_keys', tuple())
    if not sorted_keys:
        return json.dumps(data)
    else:
        out_list = []
        for element in data:
            element_list = []
            for key in sorted_keys:
                if key in element:
                    element_list.append(json.dumps({key: element[key]}))
            out_list.append('{{{}}}'.format(','.join((s[1:-1] for s in element_list))))
        return '[{}]'.format(','.join(out_list))

You use it like this:

json_string = json_dumps_sorted([
    {
        "key": "numberpuzzles1",
        "url": "number-puzzle-i.html",
        "title": "Number Puzzle I",
        "category": "nestedloops",
        "points": "60",
        "n": "087"
    }, {
        "key": "gettingindividualdigits",
        "url": "getting-individual-digits.html",
        "title": "Getting Individual Digits",
        "category": "nestedloops",
        "points": "80",
        "n": "088"
    }
], sorted_keys=(
    'key', 
    'url', 
    'title', 
    'category',
    'flags', 
    'points', 
    'n'
))
0
votes

Compact yet powerful recursive implementation with "prepended" and "appended" keys: https://gist.github.com/jeromerg/91f73d5867c5fa04ee7dbc0c5a03d611

def sort_recursive(node, first_keys, last_keys):
    """ Sort the dictionary entries in a whole JSON object tree"""
    fixed_placements = {
        **{key: (0, idx) for idx, key in enumerate(first_keys)},
        **{key: (2, idx) for idx, key in enumerate(last_keys)},
    }
    return _sort_recursive(node, lambda key: fixed_placements.get(key, (1, key)))


def _sort_recursive(node, key_fn):
    if isinstance(node, list):
        return [_sort_recursive(val, key_fn) for val in node]
    elif isinstance(node, dict):
        sorted_keys = sorted(node.keys(), key=key_fn)
        return {k:_sort_recursive(node[k], key_fn) for k in sorted_keys}
    else:
        return node
-1
votes

Thanks. I needed to put a timestamp key:value at the top of my JSON object no matter what. Obviously sorting the keys screwed this up as it starts with "t".

Using something like this, while putting the timestamp key in the dict_data right away worked:

d = collections.OrderedDict(dict_data)