我正在学习如何将 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/