python无法加载具有utf-8编码的json文件

标签 python json urllib2

使用以下python代码:

filePath = urllib2.urlopen('xx.json')
fileJSON = json.loads(filePath.read().decode('utf-8'))

xx.json 的样子:

{
    "tags": [{
        "id": "123",
        "name": "Airport",
        "name_en": "Airport",
        "name_cn": "机场",
        "display": false
    }]
}

我看到以下异常:

fileJSON = json.loads(filePath.read().decode('utf-8'))
    File "/usr/lib64/python2.7/json/__init__.py", line 339, in loads
        return _default_decoder.decode(s)
    File "/usr/lib64/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    File "/usr/lib64/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
    ValueError: No JSON object could be decoded

当我还在 read() 后面添加 .decode('utf-8') 时,代码在将汉字添加到 json 文件之前工作。

我不确定需要做什么?

最佳答案

$ wget https://s3.amazonaws.com/wherego-sims/tags.json 
$ file tags.json 
tags.json: UTF-8 Unicode (with BOM) text, with CRLF line terminators

此文件以字节顺序标记 (EF BB BF) 开头,这在 JSON ( JSON Specification and usage of BOM/charset-encoding ) 中是非法的。您必须首先使用 Python 中的 'utf-8-sig' 对此进行解码,以获得有效的 JSON unicode 字符串。

json.loads(filePath.read().decode('utf-8-sig'))

值得一提的是,Python 3(你应该使用它)在这种情况下会给出一个特定的错误并指导你处理这个格式错误的文件:

json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)

也就是说,通过指定您希望丢弃 BOM(如果它存在的话)(同样,在 UTF-8 中使用它不是常规的,特别是对于始终以 UTF-8 编码的 JSON,所以它比无用更糟糕):

>>> import json
>>> json.load(open('tags.json', encoding='utf-8-sig'))

关于python无法加载具有utf-8编码的json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48174702/

相关文章:

Python 错误 - int 对象没有属性

mysql - 存储访问器问题 : Can't read old already stored json object serialized ( hash ) values in mysql database in Rails 4

php - 使用 php 循环创建 JSON 对象

python - urllib 下载的文件与我手动下载的文件不同

python - CPython - 在主线程中锁定 GIL

python - 带有 SVM 的 GridSearch 产生 IndexError

python - 在 Celery 中,使用多个队列是否会对性能产生重大影响

mysql - PHP 获取 JSON 并通过 PDO 插入数据库

Python:如何在 POST 请求中发送 html 代码

python urllib2.URL错误处理