美文网首页
Python各种坑--JSON.load成Unicode

Python各种坑--JSON.load成Unicode

作者: 大明白 | 来源:发表于2015-09-25 16:00 被阅读8981次

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可能更好。

相关文章

网友评论

      本文标题:Python各种坑--JSON.load成Unicode

      本文链接:https://www.haomeiwen.com/subject/foqwcttx.html