Python中解析JSON并同时进行自定义编码处理实例

yipeiwu_com6年前Python基础

在对文件内容或字符串进行JSON反序列化(deserialize)时,由于原始内容编码问题,可能需要对反序列化后的内容进行编码处理(如将unicode对象转换为str)。

在Python中,一种方式是先使用json.load或json.loads反序列化得到dict对象,然后对这个dict对象进行编码处理。

但其实在json.load与json.loads中,有可选参数object_hook。通过使用此参数,可以对反序列化得到的dict直接进行处理,并使用处理后新的dict替代原dict返回。

使用方法为:

复制代码 代码如下:

d = json.loads(json_str, object_hook=_decode_dict)

附Shadowsocks中使用的_decode_dict与_decode_list:

复制代码 代码如下:

def _decode_list(data):
    rv = []
    for item in data:
        if isinstance(item, unicode):
            item = item.encode('utf-8')
        elif isinstance(item, list):
            item = _decode_list(item)
        elif isinstance(item, dict):
            item = _decode_dict(item)
        rv.append(item)
    return rv
 
def _decode_dict(data):
    rv = {}
    for key, value in data.iteritems():
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        elif isinstance(value, list):
            value = _decode_list(value)
        elif isinstance(value, dict):
            value = _decode_dict(value)
        rv[key] = value
    return rv

参考:
1.https://docs.python.org/2/library/json.html
2.https://github.com/clowwindy/shadowsocks/blob/master/shadowsocks/utils.py

相关文章

Python日期时间对象转换为字符串的实例

1、标准转换格式符号说明 %a 本地星期的短名称 如:Sun, Mon, ..., Sat (en_US); So, Mo, ..., Sa (de_DE) %A 本地星期全名称 如...

django之使用celery-把耗时程序放到celery里面执行的方法

1 在虚拟环境创建项目test和应用booktest(过程省略),然后安装所需的包 pip install celery==3.1.25 pip install celery-wit...

Django+Xadmin构建项目的方法步骤

Django部分 创建项目 django-admin startproject mysite #创建一个mysite项目 运行简易服务器 python manage.py r...

python PIL模块与随机生成中文验证码

python PIL模块与随机生成中文验证码

在这之前,你首先得了解Python中的PIL库。PIL是Python Imaging Library的简称,PIL是一个Python处理图片的库,提供了一系列模块和方法,比如:裁切,平移...

跟老齐学Python之关于循环的小伎俩

不是说while就不用,比如前面所列举而得那个猜数字游戏,在业务逻辑上,用while就更容易理解(当然是限于那个游戏的业务需要而言)。另外,在某些情况下,for也不是简单地把对象中的元素...