python - 给出错误 "the JSON object must be str, not ' 字节'“

标签 python json python-requests

我正在学习如何将 elasticsearch 与 python 结合使用的教程(link= https://tryolabs.com/blog/2015/02/17/python-elasticsearch-first-steps/#contacto ) 我遇到了这个错误。

import json
    r = requests.get('http://localhost:9200') 
    i = 1
    while r.status_code == 200:
        r = requests.get('http://swapi.co/api/people/'+ str(i))
        es.index(index='sw', doc_type='people', id=i, body=json.loads(r.content))
        i=i+1

    print(i)

TypeError: JSON 对象必须是 str,而不是 'bytes'

最佳答案

您使用的是 Python 3,而这篇博文是针对 Python 2 的。 Python 3 json.loads() 函数需要解码的 unicode 文本,而不是 response.content 返回的原始响应字节串。

与其使用 json.loads(),不如使用 requests 为您正确解码 JSON,方法是使用 response.json() 方法:

es.index(index='sw', doc_type='people', id=i, body=r.json())

关于python - 给出错误 "the JSON object must be str, not ' 字节'“,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235787/

相关文章:

ROBOT 中的 Json 处理

python-3.x - Beautifulsoup 解析千页

python - 规范化 numpy 数组

python - 如何使用每个选择的模板覆盖 ModelChoiceField/ModelMultipleChoiceField 默认小部件

python - sendgrid python api取消订阅和管理列表标签

c# - Linq查询到Json字符串

python - pip3 输出换行符而不是安装

arrays - SnapLogic - 更改映射器中的数组元素

Python 请求 : downloaded image is corrupted

python - 无法使用 scrapy 或 requests 向 API 发送请求