如何解决复杂嵌套Json中的Key错误

问题描述 投票:0回答:1

我不断收到关键错误“注释”。注释位于嵌套响应中。我该如何解决这个问题?我已经包含了 json 的示例。 按请求添加回溯。

    Traceback (most recent call last):
  File "/Users/xxxxxx/Documents/code/trade show w notes", line 16, in <module>
    target = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (contact["company_name"], contact["location"], contact["summary"], contact["job_title"], contact["name"], contact["job_industry"], contact["email"], contact["first_name"], contact["last_name"], contact["notes"])
KeyError: 'notes'

\

"data": [
    {
        "team_id": 53806,
        "name": "Nicholas Bancroft Cooke",
        "first_name": "Nicholas",

        ],
        "email": null,
        "metadata": null,
        "qualification": [
            {
                "qualification_id": 17573056,
                "qualification": "connected",

                "notes": null,

\

     page = 1
     url = "https://teams-api.grip.events/1/team/53806/event/123721/member/236388/contact/inbound_lead/reviewed?page=1"
     headers = {
         'authorization': 'Bearer eaf3bd4b-6861-4ca2-a86e-3a96c73deac0',
}
data = ["company_name", "job_title", "name",  "job_industry", "summary", "notes", "location", "first_name", "last_name", "email"]
with open("list31.txt", "w", encoding='utf-8') as f: #added " encoding='utf-8' "
         for page in range(1, 1000):
             response = requests.get(url=url, headers=headers).json()
             contacts = response["data"]
             for contact in contacts:
                 target = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (contact["company_name"], contact["location"], contact["summary"], contact["job_title"], contact["name"], contact["job_industry"], contact["email"], contact["first_name"], contact["last_name"], contact["notes"])
                 f.write(target + "\n")
                 print(target)
python json web-scraping get
1个回答
1
投票

如果您指的是

notes
下的
qualification
键。

那么应该是:

contact["qualification"][0]["notes"]

这里

contact["qualification"]
是一个列表。如果有任何机会 contact["qualification"] 是一个空列表,它将引发
IndexError
。你需要用
try-catch
if-clause

来处理它
© www.soinside.com 2019 - 2024. All rights reserved.