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中解析JSON并同时进行自定义编码处理实例到此结束。精彩的人生总有精彩的理由,笑到最后的才会笑得最甜。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python3内置模块之json编码解码方法详解