python递归实现字典中的Unicode对象encode成str

来源:互联网 发布:淘宝基础版全屏店招 编辑:程序博客网 时间:2024/06/05 15:50

Python自带的Json库会把json文件load成Unicode对象。如果想要变成str对象的话,就要自己去encode。个人认为这是python2.7中存在的一个坑,不过据说python3.x中此坑已修复。
下面上代码,是在网上找到的,亲测好用。

def byteify(input):    if isinstance(input, dict):        return {byteify(key): byteify(value) for key, value in input.iteritems()}    elif isinstance(input, list):        return [byteify(element) for element in input]    elif isinstance(input, unicode):        return input.encode('utf-8')    else:        return input

这个函数递归的把list和dict里的Unicode对象encode成str。
当然,这种方式是无奈之举。递归的效率我们都懂得,谁有好的方法,要留言告知哦,收下我的膝盖!

1 0
原创粉丝点击