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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-21 我要评论
想了解Python中解析JSON并同时进行自定义编码处理实例的相关内容吗,在本文为您仔细讲解Python解析JSON并自定义编码的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们