pythonjsongmail-api

How to get nested data in Gmail API and JSON with Python


I'm having trouble accessing nested values and keys in Gmail's API for Python. I'm getting close but I don't know how to access the values of this. How do I extract the data from the 'Subject' and the "From" sections.

for message in messages:
    msg = service.users().messages().get(userId='me', id=message['id']).execute()
    subject = msg['payload']['headers']
    for values in subject:
        name = values['name'] #This only prints the values "From" and "Subject" by itself not with the actual subject.
        print(values)
        print("\n")

The print(values) returns the following JSON data (there's dozens more lines and it's not always the same count, so I'm not sure a hard coded integer will help.

{'name': 'From', 'value': 'Duolingo <hello@duolingo.com>'}
{'name': 'Subject', 'value': '🗞 Your weekly progress report'}

How do I get just the data to the right of "value" in both of these? For example, "Your weekly progress report"?


Solution

  • Adding a variable value = values['value'] should give you the value from that output

    It looks like what you have labelled subject is actually a combination of subject, who it's from and by the sounds of it other data so I might change that variable to email_data

    so the resulting code would be

    for values in email_data:
      name = values['name']
      value = values['value']
    
      print(values)
      print("\n")