python - json.解码器.JSONDecodeError : Unexpected UTF-8 BOM (decode using utf-8-sig)

标签 python json django rest

所以我的目标是使用 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

最佳答案

您从该端点获得的响应不是 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 .

关于python - json.解码器.JSONDecodeError : Unexpected UTF-8 BOM (decode using utf-8-sig),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42526809/

相关文章:

c# - JsonSerializer 不包含 Parse 的定义

Django 响应中间件 : Get name of view which created the response

Django - 在提交时保存数据但不重新加载 View

python - MyPy 需要派生类变量的类型注释

python - 使用 keras 函数式 API 构建(预训练的)CNN+LSTM 网络

python - 类型错误:不支持的操作数类型/: 'list' 和 'int'

PHP 将具有多条记录的 XML 文件转换为 JSON

python - 如何在matplotlib中突出显示多条曲线中最低的曲线(包络线)

ios - 解析云推送通知正在推送给所有用户而不是目标用户

Javascript .on ('click' 不适用于跨度