用python搜索JSON响应

2024-06-16 08:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我找了又找,但还是搞不清楚。下面是我从web服务API中获取的JSON数据:

{
  "total_count": 673, 
  "items": [
    {
      "hap": "delivered", 
      "message": "Delivered: no-reply@example.com \u2192 jon.doe@gmail.com 'Some Email subject'", 
      "type": "info", 
      "created_at": "Wed, 19 Aug 2015 18:38:54 GMT", 
      "message_id": "20150819183853.13720.31771@example.com"
    }, 
    {
      "hap": "accepted", 
      "message": "Accepted: no-reply@example.com \u2192 jon.doe@gmail.com 'Subject of this email here'", 
      "type": "info", 
      "created_at": "Wed, 19 Aug 2015 18:38:53 GMT", 
      "message_id": "20150819183853.13720.31771@example.com"
    }, 
    {
      "hap": "delivered", 
      "message": "Delivered: no-reply@example.com \u2192 jane.doe@gmail.com 'Subject Line here'", 
      "type": "info", 
      "created_at": "Wed, 19 Aug 2015 18:37:50 GMT", 
      "message_id": "20150819183749.13738.20180@example.com"
    },

挑战是我试图在“message”:块中搜索“message”:位置中“\u2192”后面的to email地址。在

我创建了一个python脚本,它将“message”中的所有条目转储起来:但是我无法用特定的电子邮件地址来过滤它。在

^{pr2}$

Tags: noinfocommessageexampletypereplygmail
3条回答

尝试:

re.findall("[^@ ]+@[^@]+\.[^@ ]+", data['message'].split("\u2192")[1])[0]

首先,我用字符\u2192data['message']分成两部分,然后进行第二部分。我试着在第二部分找到所有的电子邮件,只选择第一部分,因为这是你要找的。在

使用json.loads来解决这个问题。在

>>> json.loads('"Delivered: no-reply@example.com \u2192 jane.doe@gmail.com"')
'Delivered: no-reply@example.com → jane.doe@gmail.com'

这些“应该”中的任何一个都有效。在

由于您已经知道电子邮件地址,因此只需在字符串中搜索确切的电子邮件地址。这里有几个选项。您可以使用正则表达式(这可能有点过头了,因为这不是一个模式,而是一个已知的字符串)。您也可以只在字符串中搜索已知的电子邮件地址。在

您可以根据消息的布尔值来决定是否应该在这两种情况下使用该消息。在

选项1

正则表达式

https://docs.python.org/3.5/library/re.html#match-objects

import re

email_address = "email_address_you_know@somewhere.com"

for data in j['items']:
    match = re.search(email_address, data['message'])
    if match:
        print data['message']

方案2

在邮件中搜索电子邮件地址字符串

^{pr2}$

相关问题 更多 >