关于python中json load出来编码为unicode的问题的解决

技术方法来源网址:

http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-Python


昨天遇到一个问题:

把一个字典 用json.dump(f,data)到文件里面

然后再从另外一端json.load(f)取出字典

发现字典的键值和内容都成了unicode

例如:{u"name":u"value"}


原因:

查阅以后发现是python写入时候编码都先中间转化成了unicode

如果说我需要不带u的东西

我要解码


网上有很多:

我试了下,下面是两个都可以生效的方案

1.

>>> import json
>>> import yaml
>>> list_org = ['a', 'b']>>> list_dump = json.dumps(list_org)>>> list_dump
'["a", "b"]'>>> json.loads(list_dump)[u'a', u'b']>>> yaml.safe_load(list_dump)['a', 'b']

2 用json 的hook函数来解决

import json

def json_load_byteified(file_handle):
    return _byteify(
        json.load(file_handle, object_hook=_byteify),
        ignore_dicts=True
    )

def json_loads_byteified(json_text):
    return _byteify(
        json.loads(json_text, object_hook=_byteify),
        ignore_dicts=True
    )

def _byteify(data, ignore_dicts = False):
    # if this is a unicode string, return its string representation
    if isinstance(data, unicode):
        return data.encode('utf-8')
    # if this is a list of values, return list of byteified values
    if isinstance(data, list):
        return [ _byteify(item, ignore_dicts=True) for item in data ]
    # if this is a dictionary, return dictionary of byteified keys and values
    # but only if we haven't already byteified it
    if isinstance(data, dict) and not ignore_dicts:
        return {
            _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
            for key, value in data.iteritems()
        }
    # if it's anything else, return it in its original form
    return data


信息来源参考:

http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值