为了账号安全,请及时绑定邮箱和手机立即绑定

如何遍历 JSON 对象

如何遍历 JSON 对象

绝地无双 2021-10-10 14:39:10
我从 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**}
查看完整描述

2 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

您必须使用 library 将生成的搅拌解析为字典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"]])

# ...


查看完整回答
反对 回复 2021-10-10
?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

将 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]就用于访问数组的第一个元素。如果要访问数组的所有元素,则必须遍历数组。


查看完整回答
反对 回复 2021-10-10
  • 2 回答
  • 0 关注
  • 153 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号