2017-04-05 117 views
4

我正在學習如何在python中使用elasticsearch(link = https://tryolabs.com/blog/2015/02/17/python-elasticsearch-first-steps/#contacto)我遇到了這個錯誤。給出錯誤「JSON對象必須是str,而不是'字節'」

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) 

類型錯誤:JSON對象必須str的,而不是 '字節'

回答

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()) 
相關問題