Python2 json:使用字符串而不是unicode加载

时间:2017-02-21 20:50:53

标签: python json string dictionary

我有一个json字符串,我想使用内置的json模块解析成字典。我可以使用loads()执行此操作,如下所示:

>>> j = '''{
...   "first": 1,
...   "second": "two",
...   "third": {
...     "first": "one",
...     "second": null
...   }
... }'''
>>> d = json.loads(j)
>>> pprint(d)
{u'first': 1,
 u'second': u'two',
 u'third': {u'first': u'one',
            u'second': None}}

问题是所有加载为unicode。有没有办法强制python将所有内容加载为string?或者,有一种简单的方法可以在创建dict后进行深度转换。

注意:因为我知道人们会问,可以安全地假设我得到的键和值只包含ASCII字符和符号,所以我对特殊字符没有问题。

1 个答案:

答案 0 :(得分:4)

您可以向json.loads()提供object_hookobject_pairs_hook参数。

from pprint import pprint
import json

def str_hook(obj):
    return {k.encode('utf-8') if isinstance(k,unicode) else k :
            v.encode('utf-8') if isinstance(v, unicode) else v
            for k,v in obj}

j = '''{
  "first": 1,
  "second": "two",
  "third": {
    "first": "one",
    "second": null
  }
}'''
d = json.loads(j, object_pairs_hook=str_hook)
pprint(d)