出现错误"JSON对象必须为str,而不是'bytes'". [英] Giving error "the JSON object must be str, not 'bytes' "

查看:129
本文介绍了出现错误"JSON对象必须为str,而不是'bytes'".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循一个教程,该教程如何将python用作Elasticsearch(link = https://tryolabs.com/blog/2015 /02/17/python-elasticsearch-first-steps/#contacto )我遇到了此错误.

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:JSON对象必须为str,而不是"bytes"

TypeError: the JSON object must be str, not 'bytes'

推荐答案

您正在使用Python 3,而该博客文章则针对Python 2. Python 3 json.loads()函数期望已解码的 unicode文本,而不是原始响应字节串,这是response.content返回的结果.

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.

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

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())

这篇关于出现错误"JSON对象必须为str,而不是'bytes'".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆