1
{
      "status": "DOWN",
      "components": {
          "ping": {
              "status": "UP",
              "details": {
                  "version": "1.0.0",
                  "description": "dobre application",
                  "name": "SO-3113"
              }
          },
          "bridge.lock": {
              "status": "UP",
              "details": {
                  "description": "test1"
              }
          },
          "Configuration converted": {
              "status": "DOWN",
              "details": {
                  "description": "test2"
              }
          },
          "app started": {
              "status": "DOWN",
              "details": {
                  "description": "test3"
              }
          }
      }
  }

I need to get the name of first component with DOWN status ("Configuration converted" in above json). So far i managed to get only .details.description of it:

jq -c '.components| .[] | select( .status | contains("DOWN")) .details.description' | head -1

How can I get the name (key) of component? ("Configuration converted")

apena
  • 2,091
  • 12
  • 19
dobre
  • 15
  • 5
  • I don´t get clear your question, I executed your query with your json in https://jqplay.org/ and it returned to me: "test2" "test3". Could you said me what is your desired output please? – sirandy Aug 28 '20 at 14:25
  • need "Configuration converted" because this is first contains "DOWN". Sorry for my bad english – dobre Aug 28 '20 at 14:40

2 Answers2

1

You can use to_entries to get the key/values of your components , then select the first one with down status:

first(.components | to_entries | .[] | select( .value.status == "DOWN") | .key)

Run it on jqplay

yaya
  • 7,675
  • 1
  • 39
  • 38
  • also note that the order of object keys do not have a real meaning, if you want to preserve order ,you should use arrays instead of object : https://stackoverflow.com/a/7214316/4718434 – yaya Aug 28 '20 at 15:40
  • 1
    It would be better to avoid `contains/1`, which has complex semantics at best, and does not seem to match the requirements here. A check using `==` should suffice. – peak Aug 28 '20 at 20:42
  • @peak Agree, Updated the answer. – yaya Aug 28 '20 at 21:52
0

You could use to_entries function to convert the objects within .components into key/value pairs and provide an expression that selects the first object matching the condition and retrieve its key

.components | 
to_entries  | 
map(select(.value.status == "DOWN"))[0].key
Inian
  • 80,270
  • 14
  • 142
  • 161