【问题标题】:How to get specific key from Gmail API json with Python?如何使用 Python 从 Gmail API json 获取特定密钥?
【发布时间】:2020-04-24 11:52:11
【问题描述】:

在 Python Gmail API 文档中,get 函数提供 json 输出,我可以访问“sn-p”数据。我想访问“标题”键的“值”信息。我觉得这应该只是获取多级 JSON 数据,但它正在逃避我。有人可以帮帮我吗?

http://googleapis.github.io/google-api-python-client/docs/dyn/gmail_v1.users.messages.html#get

{ # An email message.
      **"headers": [ # List of headers on this message part. For the top-level message part, representing the entire message payload, it will contain the standard RFC 2822 email headers such as To, From, and Subject.**
        {
          "name": "A String", # The name of the header before the : separator. For example, To.
          **"value": "A String", # The value of the header after the : separator. For example, someuser@example.com.**
        },
      ],
    "snippet": "A String", # A short part of the message text.
    "raw": "A String", # The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied.
    "sizeEstimate": 42, # Estimated size in bytes of the message.
    "threadId": "A String", # The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met:
        # - The requested threadId must be specified on the Message or Draft.Message you supply with your request.
        # - The References and In-Reply-To headers must be set in compliance with the RFC 2822 standard.
        # - The Subject headers must match.
    "labelIds": [ # List of IDs of labels applied to this message.
      "A String",
    ],
    "id": "A String", # The immutable ID of the message.
  }
        for message in messages:
            msg = service.users().messages().get(userId='me', id=message['id']).execute()
            print(msg['snippet']) # This works
            print(msg['value']) # This doesn't and I tried ['headers']['value'] also.
            print("\n")
            time.sleep(1)
Traceback (most recent call last):
  File "C:/Users/Notebook/PycharmProjects/Jarvis/Gmail.py", line 65, in <module>
    main()
  File "C:/Users/Notebook/PycharmProjects/Jarvis/Gmail.py", line 58, in main
    print("New Message: " + msg['value'])
KeyError: 'value'

【问题讨论】:

    标签: python json gmail-api


    【解决方案1】:

    "value" 存在于标头中。您可以使用msg["headers"][0]["value"]访问它

    【讨论】:

    • 感谢您的快速响应,但它显示 KeyError: "headers"。我也尝试不使用 [0] 索引,但它不起作用。
    【解决方案2】:

    所以,我在 JSON 文件上做了一个漂亮的打印,我认为 Python Gmail API 是错误的。我实际上正在寻找的标题和相应数据位于“有效负载”部分。这是获取数据的有效方法还是我做错了?

             for message in messages:
                msg = service.users().messages().get(userId='me', id=message['id']).execute()
                message_from = msg['payload']['headers'][4]
                print("You have a new message from: " + message_from['value'])
                print(msg['snippet'])
                print("\n")
                time.sleep(1)
    

    【讨论】:

    • 要了解数据结构,请使用 Try this API developers.google.com/gmail/api/v1/reference/users/messages/get 。您会看到响应 JSON 将类似于 "payload": { "partId": "", "mimeType": "text/plain", "filename": "", "headers": [ {... 因此,正如您正确假设“标头”是“有效负载”的一部分。
    • @ziganotschka 太棒了,谢谢。所以我测试了我的代码,不同的电子邮件有不同的“标题”,所以我对 [4] 索引的引用每次都不会出现相同的内容。除了键值对还有其他方法吗?
    • 您可能想在标题中搜索带有"name": "From"的标题
    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多