如何遍历 JSON 对象

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


绝地无双
浏览 155回答 2
2回答

慕容森

您必须使用 library 将生成的搅拌解析为字典json,然后您可以通过循环遍历 json 结构来遍历结果,如下所示:import jsonraw_output = '{"ParsedResults": [ { "Tex...' # your api responsejson_output = json.loads(raw_output)# iterate over all listsphone_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"]])# ...

海绵宝宝撒

将 API 响应存储到变量。让我们称之为response。现在使用json模块将 JSON 字符串转换为 Python 字典。import jsonresponse_dict = json.loads(response)现在遍历response_dict以获取所需的文本。phone_number = response_dict["ParsedResults"][0]["TextOverlay"]["Lines"][0]["Words"][0]["WordText"]只要字典值是数组,[0]就用于访问数组的第一个元素。如果要访问数组的所有元素,则必须遍历数组。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python