26

只是试图测试非常简单的 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())

它给了我错误信息:

TypeError:不能在类似字节的对象上使用字符串模式”

我假设这与b

urlopen从导入urllib.request,并且正在运行 Python 3。

有任何想法吗?

4

5 回答 5

32

read() 中的内容是字节类型,因此您需要先将其转换为字符串,然后再尝试将其解码为 json 对象。

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

于 2012-12-12T17:29:35.853 回答
6

您需要检查Content-Type标头中指定的字符集并在将其传递给json.load*().

于 2012-06-01T07:30:37.043 回答
6

它运作良好:

def myView(request):
    encoding = request.read().decode("utf-8")
    dic = json.loads(encoding)
    print(dic)
于 2014-03-05T19:29:14.550 回答
0

urllib 正在返回一个字节数组,我假设它是 py3 中的默认值,而 json 需要一个字符串。在调用 json 调用之前,尝试将返回值包装在 str() 调用中

j = str(urlopen('http://similarsitesearch.com/api/similar/ebay.com').read())
json.loads(j)
于 2012-06-01T07:29:22.817 回答
0

看起来像一个字节文字。研究如何使用 http 获取数据,或者 API 如何在标头中返回数据。

于 2012-06-01T07:31:41.500 回答