zoukankan      html  css  js  c++  java
  • 解决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]: 
  • 相关阅读:
    2017.12.13T19_B2_6.4内部类
    2017.12.13T19_B2_6.3内部类
    python--spider模拟登录
    Redis数据库
    python--spider验证码
    python--Selenium(动态渲染页面爬取)
    python--Ajax
    python绘图实例
    python绘图
    Numpy库收尾(20190806)
  • 原文地址:https://www.cnblogs.com/Jerryshome/p/3209996.html
Copyright © 2011-2022 走看看