3

试图从需要登录的 url 解析 json。在这里包括我的所有代码,因为我不确定错误在哪里。

try: import simplejson as json
except ImportError: import json
import urllib2

username = 'user'
password = '1234'
url = "https://www.blah.com/someplace"

# set up the username/password/url request
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, "https://www.blah.com", username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
request = urllib2.Request(url)
response = opener.open(request)

# option 1
json_object = json.loads(str(response))

#option 2
json_object = json.loads(response)

如果我使用选项 1 运行代码(注释掉选项 2),我会收到此错误:

Traceback (most recent call last):
  File "jsontest.py", line 22, in <module>
    json_object = json.loads(str(request))
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 413, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 420, in raw_decode
    raise JSONDecodeError("No JSON object could be decoded", s, idx)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

如果我运行选项 2:

Traceback (most recent call last):
  File "jsontest.py", line 23, in <module>
    json_object = json.loads(request)
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 413, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

据我所知,我的示例 JSON 是有效的:

{"set1":[{"data1":"411","data2":"2033","data3":"1","data4":"43968077","data5":"217","data6" :"106828","data7":[]}], "set2":{"data8":"411","data9":"2033","data10":"43968077","data11":"217223360" "data12":"106828"}}

simplejson 版本 = 2.3.2,Python 2.7.3

这一切都很新,所以任何指针都会非常有帮助。

4

2 回答 2

8

您想解码响应,而不是请求:

json_object = json.load(response)

响应是一个类似文件的对象,因此您可以使用.load()json 库直接读取它。

或者(以使用一些临时内存为代价),使用.loads()具有完全读取响应的函数:

json_object = json.loads(response.read())

请注意,python 2.7 已经包含 simplejson 库,重命名为json

import json
于 2012-09-07T22:54:28.223 回答
1

您需要使用响应,而不是请求(可能只是一个错字?),但您还需要使用response.read()来获取 HTTP 响应的正文:

json_object = json.loads(response.read())
于 2012-09-07T22:57:00.147 回答