byteify

Python自带的Json库会把json文件load成Unicode对象。如果想要变成str对象的话,就要自己去encode。
祭出大法...

#请叫我搬运工
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。当然,我不觉得这是the right way。使用yaml里的json来代替官方自带的json可能更好。



作者:大明白
链接:https://www.jianshu.com/p/edc9865bc09b
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文地址:https://www.cnblogs.com/yuanzhenliu/p/8759665.html