解决python中json模块loads出来的结构都是unicode的问题

在使用python的json模块对json字串反序列化成python对象的时候出现的字符串都是unicode类型,而不是python内置的str类型。在某种使用场景下用户必须做显式的转换才能正常使用,徒增一些麻烦,为解决这一问题封装下述函数。

def convert(input):
    if isinstance(input, dict):
        return {convert(key): convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

对于采用python反序列化后的python对象再调用一次convert函数即可,当然也可以再loads的时候指定object_hook即可。

示例如下:

In [38]: data = {'key1': 'data1',
   ....:        'key2': 'data2'}

In [39]: json_str = json.dumps(data)

In [40]: print json_str
{"key2": "data2", "key1": "data1"}

In [41]: print json.loads(json_str)
{u'key2': u'data2', u'key1': u'data1'}

In [42]: print convert(json.loads(json_str))
{'key2': 'data2', 'key1': 'data1'}

In [43]: 
原文地址:https://www.cnblogs.com/Jerryshome/p/3209996.html