4

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'

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Taimour Ali
  • 96
  • 2
  • 5

1 Answers1

8

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())
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343