Python 2.6中有什么方法可以向JSON的sort_keys提供自定义键或cmp函数?
我有一个来自JSON的字典列表,如下所示:
[ { "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" } ]
…我已将其存储到list变量中assigndb。我希望能够加载JSON,对其进行修改,然后使用dumps(或其他方式)将其序列化回去,同时保持 键 的 顺序不变 。
assigndb
dumps
到目前为止,我已经尝试过以下方法:
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)
…但是当然dumps不像那样支持自定义键list.sort()。有风俗的东西JSONEncoder吗?我似乎无法继续前进。
list.sort()
JSONEncoder
这有点丑陋,但是如果tokland的解决方案对您不起作用:
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) + "]"