【问题标题】:json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig)json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig)
【发布时间】:2017-07-20 11:45:34
【问题描述】:

所以我的目标是使用 ISO Alpha-2 国家/地区代码找到一个国家/地区的名称。我认为这是第一次尝试 RESTful API(确切地说是World Bank API)的好时机。我开始使用this tutorial 来实现我的目标,似乎requests.get() 是我问题的答案,我试了一下,得到了这个:

(InteractiveConsole)
>>> import requests
>>> resp = requests.get('http://api.worldbank.org/countries/br')
>>> resp
<Response [200]>
>>> resp.json()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\models.py", line 866, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\json\__init__.py", line 315, in loads
    s, 0)
json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)

我不太确定出了什么问题或它告诉我该怎么做(我对 JSON 不太熟悉)。对此有何解释以及如何解决?

我正在使用:

Windows 7 64 位

Python 3.5.1

Django 1.10

requests 包 2.13.0

【问题讨论】:

  • 您确定您发送的GET 请求以json 格式返回响应吗?
  • FWIW,Unicode 标准不推荐使用 UTF-8 格式的 BOM,但很多 Windows 软件都坚持这样做。 :( 详情见en.wikipedia.org/wiki/Byte_order_mark#UTF-8

标签: python json django rest


【解决方案1】:

您从该端点获得的响应不是 JSON。 因此,即使使用json.loads(),也无法将其解析为 JSON。

它返回一个必须以不同方式解析的 XML。

你可以使用:

import requests
import xml.etree.ElementTree 

resp = requests.get('http://api.worldbank.org/countries/br')
root = xml.etree.ElementTree.fromstring(resp.content)
print( root.find("{http://www.worldbank.org}country")[1].text )

要了解如何正确解析 XML 数据,您应该阅读 documentation

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2021-12-21
    • 2011-07-21
    • 2016-05-04
    • 2021-08-01
    相关资源
    最近更新 更多