给出错误" JSON对象必须是str,而不是' bytes' "

时间:2017-04-05 15:39:05

标签: python json python-requests

我正在学习如何在python中使用elasticsearch(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'

1 个答案:

答案 0 :(得分:8)

您使用的是Python 3,而博客文章的目标是Python 2。 Python 3 json.loads()函数需要解码的 unicode文本,而不是原始响应字节字符串,这是response.content返回的内容。

不是使用json.loads(),而是使用requests方法将其保留给response.json()以正确解码JSON

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