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

在对文件内容或字符串进行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中,可以使用wave模块来读取双通道(立...
简介 一个用python实现的科学计算,包括: 1、一个强大的N维...
使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登...
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登...
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接...
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密...