从urlopen.read使用“之类字节对象”与JSON?(Use “byte-like objec

2019-07-29 16:17发布

只是想测试一下很简单的Python JSON的命令,但我遇到了一些麻烦。

urlopen('http://www.similarsitesearch.com/api/similar/ebay.com').read()

应该输出

'{"num":20,"status":"ok","r0":"http:\\/\\/www.propertyroom.com\\/","r1":"http:\\/\\/www.ubid.com\\/","r2":"http:\\/\\/www.bidcactus.com\\/","r3":"http:\\/\\/www.etsy.com\\/","r4":"http:\\/\\/us.ebid.net\\/","r5":"http:\\/\\/www.bidrivals.com\\/","r6":"http:\\/\\/www.ioffer.com\\/","r7":"http:\\/\\/www.shopgoodwill.com\\/","r8":"http:\\/\\/www.beezid.com\\/","r9":"http:\\/\\/www.webidz.com\\/","r10":"http:\\/\\/www.auctionzip.com\\/","r11":"http:\\/\\/www.overstock.com\\/","r12":"http:\\/\\/www.bidspotter.com\\/","r13":"http:\\/\\/www.paypal.com\\/","r14":"http:\\/\\/www.ha.com\\/","r15":"http:\\/\\/www.onlineauction.com\\/","r16":"http:\\/\\/bidz.com\\/","r17":"http:\\/\\/www.epier.com\\/","r18":"http:\\/\\/www.sell.com\\/","r19":"http:\\/\\/www.rasmus.com\\/"}'

但我得到的是相同的字符串,用b在前面:

b'{"num":20,"status":"ok","r0":"http:\\/\\/www.propertyroom.com\\/","r1":"http:\\/\\/www.ubid.com\\/","r2":"http:\\/\\/www.bidcactus.com\\/","r3":"http:\\/\\/www.etsy.com\\/","r4":"http:\\/\\/us.ebid.net\\/","r5":"http:\\/\\/www.bidrivals.com\\/","r6":"http:\\/\\/www.ioffer.com\\/","r7":"http:\\/\\/www.shopgoodwill.com\\/","r8":"http:\\/\\/www.beezid.com\\/","r9":"http:\\/\\/www.webidz.com\\/","r10":"http:\\/\\/www.auctionzip.com\\/","r11":"http:\\/\\/www.overstock.com\\/","r12":"http:\\/\\/www.bidspotter.com\\/","r13":"http:\\/\\/www.paypal.com\\/","r14":"http:\\/\\/www.ha.com\\/","r15":"http:\\/\\/www.onlineauction.com\\/","r16":"http:\\/\\/bidz.com\\/","r17":"http:\\/\\/www.epier.com\\/","r18":"http:\\/\\/www.sell.com\\/","r19":"http:\\/\\/www.rasmus.com\\/"}'

随后,当我尝试运行

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

它给我的错误信息:

类型错误:一类字节对象上不能使用字符串模式”

这我假设有事情做与b

我进口urlopenurllib.request ,和我运行的Python 3。

有任何想法吗?

Answer 1:

从阅读()的内容类型的字节 ,所以你需要尝试将其解码成JSON对象之前将其转换为字符串。

为了字节转换为字符串,更改您的代码: urlopen('http://similarsitesearch.com/api/similar/ebay.com').read().decode("utf-8")



Answer 2:

它运作良好:

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


Answer 3:

你需要检查在指定的字符集Content-Type头和解码由它传递到前json.load*()



Answer 4:

的urllib返回一个字节数组,我假设是在PY3默认和JSON期待一个字符串。 尝试在海峡包装的返回值()调用JSON调用之前调用

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


Answer 5:

看起来像字面字节 。 调查你如何与HTTP,或如何API返回的报头中的数据得到的数据。



文章来源: Use “byte-like object” from urlopen.read with JSON?