擅长:python、mysql、java
<p>没有使json模块函数返回字节字符串而不是unicode字符串的内置选项。但是,这个简短的递归函数将任何解码的JSON对象从使用unicode字符串转换为UTF-8编码的字节字符串:</p>
<pre><code>def byteify(input):
if isinstance(input, dict):
return {byteify(key): byteify(value)
for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
</code></pre>
<p>只需在从<code>json.load</code>或<code>json.loads</code>调用获得的输出上调用此函数。</p>
<p>几条注释:</p>
<ul>
<li>要支持Python2.6或更早版本,请将<code>return {byteify(key): byteify(value) for key, value in input.iteritems()}</code>替换为<code>return dict([(byteify(key), byteify(value)) for key, value in input.iteritems()])</code>,因为直到Python2.7才支持字典理解。</li>
<li>由于此答案在整个解码对象中递归,因此它有两个不需要的性能特征,可以通过非常小心地使用<code>object_hook</code>或<code>object_pairs_hook</code>参数来避免。<a href="https://stackoverflow.com/a/33571117/1709587">Mirec Miskuf's answer</a>是目前为止唯一一个能够正确实现这一点的方法,尽管结果是,它比我的方法要复杂得多。</li>
</ul>