json响应正常工作:
obj = urllib.urlopen("http://www.omdbapi.com/?t=Fight Club")
response_str = obj.read()
response_json = simplejson.loads(response_str)
Run Code Online (Sandbox Code Playgroud)
上面的代码发出json请求,如下所示:
{
"Title":"Fight Club",
"Year":"1999",
"Rated":"R",
"Released":"15 Oct 1999",
......
"Response":"True"
}
Run Code Online (Sandbox Code Playgroud)
我现在可以睡觉了...但是
json响应无法正常工作:
obj = urllib.urlopen("https://api.stackexchange.com/2.1/answers?order=desc&sort=activity&site=stackoverflow")
response_str = obj.read()
response_json = simplejson.loads(response_str)
Run Code Online (Sandbox Code Playgroud)
上面的代码发出json请求,如下所示:
{
"items": [
{
"question_id": 18384375,
"answer_id": 18388044,
"creation_date": 1377195687,
"last_activity_date": 1377195687,
"score": 0,
"is_accepted": false,
"owner": {
"user_id": 1745001,
"display_name": "Ed Morton",
"reputation": 10453,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/99a3ebae89496eb16afe453aae97f5be?s=128&d=identicon&r=PG",
"link": "/sf/users/122150101/"
}
},
{
"question_id": 18387447,
"answer_id": 18388040,
"creation_date": 1377195667,
"last_activity_date": 1377195667,
"score": 0,
"is_accepted": false,
"owner": {
"user_id": 2494429,
"display_name": "kpark91",
"reputation": 140,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/d903a03e7c5b6d9b21ff598c632de575?s=128&d=identicon&r=PG",
"link": "/sf/users/174610061/"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
退货
JSONDecodeError at /
No JSON object could be decoded: line 1 column 0 (char 0)
Run Code Online (Sandbox Code Playgroud)
而不是使用simplejson我尝试了json,它给出了以下错误:
ValueError at /
No JSON object could be decoded
Run Code Online (Sandbox Code Playgroud)
我尝试过的和失败的:
我在有相同问题的stackoverflow上尝试了我的问题的答案,但是尽管每个人都以某种方式帮助了我,但它们都没有给出明确的解决方案
1)我检查了json内容编码是否正确
>>obj.info()
Content-Type: application/json;
charset=utf-8
Content-Length: 2398
Run Code Online (Sandbox Code Playgroud)
2)我在utf-8中解码了response_str
json.loads(response_str).decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
3)我用jsonlint检查json响应的格式
Parse error on line 1:
^
Expecting '{', '['
Run Code Online (Sandbox Code Playgroud)
出人意料的是,以下链接挽救了我的睡眠。 JSONDecodeError:预期值:第1行第1列(字符0)
基本上我在两种情况下都使用精确的代码来获取json响应,但是第二个json响应出了什么问题,唯一的区别是我注意到第二个json响应的结构与第一个不同。
请提供解释以了解该问题。
让我给你一些建议。使用工具固然urllib很棒,但您会遇到很多麻烦。因此,让我为您省去痛苦,并带领您前进requests。这是处理url请求的最佳方法。
此IDLE简短会议将演示:
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
Run Code Online (Sandbox Code Playgroud)
要安装它,只需转到命令提示符和pip install requets。requets是免费的开放源代码,它是用纯python编写的,因此安装很简单。
这是一个演示视频:

您的特定问题:

| 归档时间: |
|
| 查看次数: |
2783 次 |
| 最近记录: |