【发布时间】:2020-07-28 11:54:22
【问题描述】:
我有一个包含一些 JSON 数据的 URL。我想解析这些数据并使用 Python 转换为字典。网页上的第一行数据不是JSON格式的,所以我想在解析之前跳过第一行。网页上的数据如下所示:
expected 1 issue, got 1
{
"Issues": [
{
"issue": {
"assignedTo": {
"iD": "2",
"name": "industry"
},
"count": "1117",
"logger": "errors",
"metadata": {
"function": "_execute",
"type": "IntegrityError",
"value": "duplicate key value violates unique constraint \nDETAIL: Key (id, date, reference)=(17, 2020-08-03, ZER) already exists.\n"
},
"stats": {},
"status": "unresolved",
"type": "error"
},
"Events": [
{
"message": "Unable to record contract details",
"tags": {
"environment": "worker",
"handled": "yes",
"level": "error",
"logger": "errors",
"mechanism": "logging",
},
"Messages": null,
"Stacktraces": null,
"Exceptions": null,
"Requests": null,
"Templates": null,
"Users": null,
"Breadcrumbs": null,
"Context": null
},
],
"fetch_time": "2020-07-20"
}
]
}
我已经尝试过运行这个脚本:
with urllib.request.urlopen("[my_url_here]") as url:
if(url.getcode()==200):
for _ in range(1):
next(url)
data = url.read()
json=json.loads(data)
else:
print("Error receiving data", url.getcode())
但我遇到了错误:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
File
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我在不使用的情况下运行它时遇到同样的错误
for _ in range(2):
next(url)
...但最后一行是“期望值:第 2 行第 1 列(字符 1)”。
有什么建议吗?谢谢
【问题讨论】:
-
您拥有的对象似乎不是有效的 JSON。先解决这个问题。
-
@baduker 你能再具体一点吗?
-
如果多个问题是“预期的”和/或“得到”的,其余数据是否仍然是单个 JSON 对象?还是会有多个单独的 JSON 片段?
-
您是否尝试验证在调用
json.loads之前收到的data是什么?
标签: python json dictionary parsing web-scraping