Python递归实现字典中的Unicode转换成str

由于josn库的loads方法会把类型全部转换成 Unicode。如果想要变成str对象的话,就要自己去encode。

试试如下代码:

1
2
3
4
5
6
7
8
9
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

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×