【问题标题】:How to traverse over JSON object如何遍历 JSON 对象
【发布时间】:2019-06-07 14:41:45
【问题描述】:

我收到来自 API 的以下响应,我想在 Python 中从此对象中提取电话号码。我该怎么做?

    {
"ParsedResults": [
    {
        "TextOverlay": {
            "Lines": [
                {
                    "Words": [
                        {
                            "WordText": "+971555389583", //this field
                            "Left": 0,
                            "Top": 5,
                            "Height": 12,
                            "Width": 129
                        }
                    ],
                    "MaxHeight": 12,
                    "MinTop": 5
                }
            ],
            "HasOverlay": true,
            "Message": "Total lines: 1"
        },
        "TextOrientation": "0",
        "FileParseExitCode": 1,
        "ParsedText": "+971555389583 \r\n",
        "ErrorMessage": "",
        "ErrorDetails": ""
    }
],
"OCRExitCode": 1,
"IsErroredOnProcessing": false,
"ProcessingTimeInMilliseconds": "308",
"SearchablePDFURL": "Searchable PDF not generated as it was not requested."**strong text**}

【问题讨论】:

  • 在python中,json(看起来{key:value}对被称为字典。python带有一个json库,可以轻松地将json字符串转换为python字典。这应该可以帮助您入门. 如果有必要,请查阅一两个教程,您应该会很快赶上进度。
  • 一路上有数组。你必须知道你是否对第一次出现感兴趣,如果有多个行或单词怎么办。
  • 我只想要 "WordText": "+971555389583",这一行
  • 您问题中的示例 JSON 无效。

标签: python json python-2.7 python-requests


【解决方案1】:

将 API 响应存储到变量中。我们就叫它response吧。

现在使用 json 模块将 JSON 字符串转换为 Python 字典。

import json

response_dict = json.loads(response)

现在遍历response_dict 获取所需的文本。

phone_number = response_dict["ParsedResults"][0]["TextOverlay"]["Lines"][0]["Words"][0]["WordText"]

只要字典值是一个数组,[0] 就用于访问数组的第一个元素。如果要访问数组的所有元素,则必须遍历数组。

【讨论】:

    【解决方案2】:

    您必须使用库 json 将生成的搅拌解析成字典,然后您可以通过循环遍历 json 结构来遍历结果,如下所示:

    import json
    
    raw_output = '{"ParsedResults": [ { "Tex...' # your api response
    json_output = json.loads(raw_output)
    
    # iterate over all lists
    phone_numbers = []
    
    for parsed_result in json_output["ParsedResults"]:
        for line in parsed_result["TextOverlay"]["Lines"]:
            # now add all phone numbers in "Words"
            phone_numbers.extend([word["WordText"] for word in line["Words"]])
    
    print(phone_numbers)
    

    您可能需要检查该进程中是否存在所有密钥,具体取决于您使用的 API,例如

    # ...
    for line in parsed_result["TextOverlay"]["Lines"]:
        if "Words" in line: # make sure key exists
            phone_numbers.extend([word["WordText"] for word in line["Words"]])
    # ...
    

    【讨论】:

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