Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

custom JSON sort_keys order in Python

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...