擅长:python、mysql、java
<p>一个想法(用2.7测试):</p>
<pre><code>import json
import collections
json.encoder.c_make_encoder = None
d = collections.OrderedDict([("b", 2), ("a", 1)])
json.dumps(d)
# '{"b": 2, "a": 1}'
</code></pre>
<p>见:<a href="http://docs.python.org/dev/library/collections.html#collections.OrderedDict" rel="nofollow noreferrer">OrderedDict</a>+<a href="http://bugs.python.org/issue6105" rel="nofollow noreferrer">issue6105</a>。<code>c_make_encoder</code>黑客似乎只是Python 2.x所需要的,并不是一个直接的解决方案,因为您必须为<code>OrderedDict</code>s更改<code>dict</code>s,但它可能仍然可用。我检查了json库(<a href="http://hg.python.org/cpython/file/e1e5423815a4/Lib/json/encoder.py#l338" rel="nofollow noreferrer">encode.py</a>),命令是硬编码的:</p>
<pre><code>if _sort_keys:
items = sorted(dct.items(), key=lambda kv: kv[0])
</code></pre>