Python中的自定义JSON sort_keys顺序 [英] custom JSON sort_keys order in Python

查看:933
本文介绍了Python中的自定义JSON sort_keys顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.6中是否可以为JSON的sort_keys提供自定义键或cmp函数?

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

我有一个来自JSON的字典列表,如下所示:

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"
  }
]

...我已将其存储到列表变量assigndb中.我希望能够加载JSON,对其进行修改,然后使用dumps(或其他任何方式)将其序列化回去,并保持键的顺序不变.

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

...但是,当然dumps不像list.sort()那样支持自定义键.带有自定义JSONEncoder的内容?我似乎无法解决问题.

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

推荐答案

这有点难看,但是如果tokland的解决方案对您不起作用:

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) + "]"

这篇关于Python中的自定义JSON sort_keys顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆