简体   繁体   中英

Select value from array json using jq

I have the following json file which this value

{
  "data": [
      {
          "id": 60573936,
          "timeCreated": 1615458564202,
          "timeUpdated": 1615458564202,
          "name": "name1",
          "desiredStatus": "UNMANAGED",
          "defaultStatus": "STARTED",
          "targets": [
              {
                  "id": 2520949,
                  "lastReportedStatus": "STOPPED"
              }, {
                  "id": 702881,
                  "lastReportedStatus": "STARTED"
              }
          ]
      }, {
          "id": 60574370,
          "timeCreated": 1615458812565,
          "timeUpdated": 1615458812565,
          "name": "name2",
          "desiredStatus": "UNMANAGED",
          "defaultStatus": "STARTED",
          "targets": [
              {
                  "id": 2520949,
                  "lastReportedStatus": "STARTED"
              }, {
                  "id": 702881,
                  "lastReportedStatus": "STOPPED"
              }
          ]
      }, {
          "id": 60574329,
          "timeCreated": 1615458775053,
          "timeUpdated": 1615458775053,
          "name": "name3",
          "desiredStatus": "UNMANAGED",
          "defaultStatus": "STARTED",
          "targets": [
              {
                  "id": 2520949,
                  "lastReportedStatus": "STOPPED"
              }, {
                  "id": 702881,
                  "lastReportedStatus": "STARTED"
              }
          ]
      }
    ]
  }

I would like to extract the "name" value only if "id"="2520949" and "lastReportedStatus"="STOPPED" using jq. In my example I would like to get "name1" and "name3". I tried using select feature but I'm not able to satisfy the "and" condition between "id" and "lastReportedStatus" key. What is the correct code with jq?

jq '.data[] 
    | select(.targets[] | .lastReportedStatus=="STOPPED" and .id==2520949)
    | .name' file.json

In this above question if I have to lastReportedStatus in the targets by specifying the id, then how can I achieve that in jq?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM