python-3.x 如何将json信息过滤成多个值?

guicsvcw  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(132)

我正在寻找一种方法来过滤客户信息到变量,我可以用来发送电子邮件。我寻找的变量之一是“nospam1@gmail.com“谁能帮我这个?
我测试的代码是:

import json

with open('notion_data.json') as json_file:
    data = json.load(json_file)

if [x for x in data['properties'] if x.get('plain_text')=='nospam1@gmail.com']:
  print("IN")
else:
  print("NOT")

The error i get: 
Traceback (most recent call last):
  File "C:\Users\stijn\PycharmProjects\notion\scrath_notion.py", line 13, in <module>
    if [x for x in data['properties'] if x.get('plain_text')=='nospam1@gmail.com']:
                   ~~~~^^^^^^^^^^^^^^
KeyError: 'properties'

Process finished with exit code 1

json文件的数据:

{
  "object": "list",
  "results": [
    {
      "object": "page",
      "id": "a94f4f2d-b965-43db-a8bf-02c1453033ee",
      "created_time": "2022-11-15T18:53:00.000Z",
      "last_edited_time": "2022-11-15T18:58:00.000Z",
      "created_by": {
        "object": "user",
        "id": "9b60ada0-dc62-441f-8c0a-e1668a878d0e"
      },
      "last_edited_by": {
        "object": "user",
        "id": "9b60ada0-dc62-441f-8c0a-e1668a878d0e"
      },
      "cover": null,
      "icon": null,
      "parent": {
        "type": "database_id",
        "database_id": "4279b28e-fd9d-4efd-b9f7-957699839dd4"
      },
      "archived": false,
      "properties": {
        "email_sender": {
          "id": "CdJY",
          "type": "rich_text",
          "rich_text": [
            {
              "type": "text",
              "text": {
                "content": "nospam2@gmail.com",
                "link": null
              }}}}}
vfh0ocws

vfh0ocws1#

你必须遍历所有的中间对象。假设有多个结果:

for result in data['results']:
    texttype = result['properties']['email_sender']['type']
    email = result['properties']['email_sender'][texttype][0]['text']['content']
    if email == 'nospam2@gmail.com':
        print("winner")

相关问题