Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving error "the JSON object must be str, not 'bytes' "

I was following a tutorial that how to use elasticsearch with python (link= https://tryolabs.com/blog/2015/02/17/python-elasticsearch-first-steps/#contacto) i faced this error.

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: the JSON object must be str, not 'bytes'

like image 706
Taimour Ali Avatar asked Feb 04 '23 17:02

Taimour Ali


1 Answers

You are using Python 3, and the blog post is aimed at Python 2 instead. The Python 3 json.loads() function expects decoded unicode text, not the raw response bytestring, which is what response.content returns.

Rather than use json.loads(), leave it to requests to decode the JSON correctly for you, by using the response.json() method:

es.index(index='sw', doc_type='people', id=i, body=r.json())
like image 180
Martijn Pieters Avatar answered Feb 07 '23 19:02

Martijn Pieters