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]: 
  • 相关阅读:
    linux中iptables的用法
    Git介绍及安装配置
    第一个shell脚本
    Nginx配置优化解读
    Python中print格式化输出
    python 程序构架浅析
    Python 常用字符串操作
    Python入门学习:网络刷博器爬虫
    vSphere SDK for Java
    vROPS中获取虚拟机在VC中的UUID
  • 原文地址:https://www.cnblogs.com/Jerryshome/p/3209996.html
Copyright © 2011-2022 走看看