Use “byte-like object” from urlopen.read with JSON?

时光毁灭记忆、已成空白 提交于 2019-12-03 10:33:33

The content from read() is of type bytes so you need to convert it to a string before trying to decode it into a json object.

To convert bytes to a string, change your code to: urlopen('http://similarsitesearch.com/api/similar/ebay.com').read().decode("utf-8")

It worked well :

def myView(request):
    encoding = request.read().decode("utf-8")
    dic = json.loads(encoding)
    print(dic)

You need to examine the charset specified in the Content-Type header and decode by that before passing it to json.load*().

urllib is returning a byte array, which I assume is the default in py3, and json is expecting a string. Try wrapping the return value in a str() call before invoking the json call

j = str(urlopen('http://similarsitesearch.com/api/similar/ebay.com').read())
json.loads(j)

Looks like a byte literal. Investigate how you get the data with http, or how the API returns the data in the headers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!