Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

jq - Extract nested properties from an array of objects

I have the following JSON file :

{
  "filter": [
    {
      "id": "id_1",
      "criteria": {
        "from": "[email protected]",
        "subject": "subject_1"
      },
      "action": {
        "addLabelIds": [
          "Label_id_1"
        ],
        "removeLabelIds": [
          "INBOX",
          "SPAM"
        ]
      }
    },
    {
      "id": "id_2",
      "criteria": {
        "from": "[email protected]",
        "subject": "subject_1"
      },
      "action": {
        "addLabelIds": [
          "Label_id_2"
        ],
        "removeLabelIds": [
          "INBOX",
          "SPAM"
        ]
      }
    }
  ]
}

And I would like to extract emails values : [email protected] and [email protected]

I have tried this command:

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

But does not work, I get this error :

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

Another point : how to display the value of "id" key, where "from" key value = [email protected] ?

So in my file id = id_1

Do you have an idea ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you only need to extract the emails from .criteria.from then this filter is enough as far as I can tell:

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

If some objects don't have a criteria object then you can filter out nulls with:

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

If you want to keep the emails equal to "[email protected]":

jq --raw-output '.filter[].criteria.from | select(. == "[email protected]")' file.json

If you want to keep the emails that start with "mail@":

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...