【问题标题】:Extract nested properties from an array of objects从对象数组中提取嵌套属性
【发布时间】:2021-01-11 16:29:35
【问题描述】:

我有以下 JSON 文件:

{
  "filter": [
    {
      "id": "id_1",
      "criteria": {
        "from": "mail@domain1.com",
        "subject": "subject_1"
      },
      "action": {
        "addLabelIds": [
          "Label_id_1"
        ],
        "removeLabelIds": [
          "INBOX",
          "SPAM"
        ]
      }
    },
    {
      "id": "id_2",
      "criteria": {
        "from": "mail@domain2.com",
        "subject": "subject_1"
      },
      "action": {
        "addLabelIds": [
          "Label_id_2"
        ],
        "removeLabelIds": [
          "INBOX",
          "SPAM"
        ]
      }
    }
  ]
}

我想提取电子邮件值:ma​​il@domain1.com 和 ma​​il@domain2.com

我试过这个命令:

jq --raw-output '.filter[] | select(.criteria.from | test("mail"; "i")) | .id'

但不起作用,我收到此错误:

jq: error (at <stdin>:1206): null (null) cannot be matched, as it is
not a string exit status 5

还有一点:如何显示“id”键的值,其中“from”键值=mail@domain1.com?

所以在我的文件中 id = id_1

你有什么想法吗?

【问题讨论】:

  • 匹配电子邮件的模式是什么?当有匹配时,您是只想保留电子邮件还是要保留整个对象?

标签: jq


【解决方案1】:

如果您只需要从.criteria.from 中提取电子邮件,那么据我所知,这个过滤器就足够了:

jq --raw-output '.filter[].criteria.from' file.json

如果某些对象没有条件对象,那么您可以使用以下方法过滤掉空值:

jq --raw-output '.filter[].criteria.from | select(. != null)' file.json

如果您想保持电子邮件等于"mail@domain1.com":

jq --raw-output '.filter[].criteria.from | select(. == "mail@domain1.com")' file.json

如果您想保留以"mail@"开头的电子邮件:

jq --raw-output '.filter[].criteria.from | select(. != null) | select(startswith("mail@"))' file.json

【讨论】:

  • 好的,谢谢。我需要提取一个特定的电子邮件值,例如:mail@domain1.com
  • @TooNetCreation 我不明白;如果您已经拥有该值,您还需要提取什么?您是否要提取与特定模式匹配的电子邮件?
  • 是的,我需要提取与特定模式匹配的电子邮件。例如:如何从 JSON 发送邮件@domain1.com?
  • 我已经用另一个问题更新了帖子 1 ;-)
【解决方案2】:

我想提取电子邮件值

有很多可能的答案,这些 在 JSON 中电子邮件地址出现的位置最不具体:

.. | objects | .from | select(type=="string")
.. | strings | select(test("@([a-z0-9]+[.])+[a-z]+$"))

【讨论】:

  • 实际上我不想显示电子邮件,我只想显示键入的特定电子邮件的 ID 值
  • 更新:问题出在我的 json 文件上,这个命令有效:.filter[] |选择(.criteria.from | 测试(“字符串”;“我”)) | .id
猜你喜欢
  • 1970-01-01
  • 2013-10-11
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多