如何遍历JSON对象

2024-09-29 23:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个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**}

Tags: 对象apifieldtopnot电话号码thiswidth
2条回答

存储对变量的API响应。我们叫它^{{cd1>}。

现在使用^{cd2>}模块将JSON字符串转换为Python字典。

import json

response_dict = json.loads(response)

现在遍历^{cd3>}以获取所需的文本。

^{pr2}$

无论字典值是数组,都使用^{{cd4>}访问数组的第一个元素。如果您想访问数组的所有元素,则必须循环遍历数组。

您必须使用库json将生成的stirng解析到字典中,然后可以通过在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,比如

^{pr2}$

相关问题 更多 >

    热门问题