Python中解析JSON并同时进行自定义编码处理实例
(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun)
在对文件内容或字符串进行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用tkinter实现一个简易能进行随机点名的界面
这篇文章主要介绍了python用tkinter实现一个简易能进行随机点名的界面,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-09-09Python3 使用pip安装git并获取Yahoo金融数据的操作
这篇文章主要介绍了Python3 使用pip安装git并获取Yahoo金融数据的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2021-04-04
最新评论