【问题标题】:Parse JSON from URL and skip first line with Python从 URL 解析 JSON 并使用 Python 跳过第一行
【发布时间】: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


【解决方案1】:

您可以通过以下代码删除第一行。

代码:

data = ''.join(data.split('\n')[1:])
print(data)

输出:

{  "Issues": [    {      "issue": {        "assignedTo": {          "iD": "2",          "name": "industry"        },        "count": "1117",        "logger": "errors",        "metadata": {          "function": "_execute",          "type": "IntegrityError",          "value": "duplicate key value violates unique constraint DETAIL:  Key (id, date, reference)=(17, 2020-08-03, ZER) already exists."        },        "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"    }  ]}

如您所见,我们实现了删除第一行。但是您的 Parsed Json 响应有问题。它的格式不正确。看看下面的图片。

在交叉线上,我们得到了额外的逗号,让解析器知道还有更多实例仍然存在,但您的响应在该范围内没有更多实例。因此,请检查用于将数据转换为 json 的代码。如果您有疑问,请写在这里。要验证您的 json,您可以查看 https://jsonlint.com/

我希望它会有所帮助... :)

【讨论】:

  • 感谢您指出 JSON 对象的错误!但是,您的拆分代码给出了“需要类似字节的对象,而不是 'str'”的错误
  • statsjohn123 是字典对象还是字符串对象?
【解决方案2】:

您可以尝试像这样加载 json:

json.loads(data.split("\n",1)[1])

这将在第一行分割字符串并使用它的第二部分。 但是我不鼓励这样做,因为您不能确定您的服务器总是会这样回复 - 尝试修复端点或找到一个返回有效 json 回复的端点。

您仍然会得到一个json.decoder.JSONDecodeError: Invalid control character at: line 14 column 68 (char 336),因为数据中有\n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多