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赋值操作方法分享

一、序列赋值: x,y,z = 1,2,3 我们可以看作:x = 1,y = 2,z = 3 二、链接赋值: x = y = 1print id(x)print id(y) 大家可以看下...

Django自带的加密算法及加密模块详解

Django 内置的User类提供了用户密码的存储、验证、修改等功能,可以很方便你的给用户提供密码服务。 默认的Ddjango使用pbkdf2_sha256方式来存储和管理用的密码,当然...

Python Flask基础教程示例代码

Python Flask基础教程示例代码

本文研究的主要是Python Flask基础教程,具体介绍如下。 安装:pip install flask即可 一个简单的Flask from flask import Flask...

python 实现list或string按指定分段

我就废话不多说了,直接上代码吧! #方法一 def list_cut(mylist,count): length=len(mylist) merchant=length//c...

django允许外部访问的实例讲解

1、关闭防火墙 service iptables stop 2、设置django 开开启django时,使用0.0.0.0:xxxx,作为ip和端口例如: python ma...