Arvind
Arvind

Reputation: 11

Select objects based on value of variable in nested objects using jq

My question is very similar to one found here -

I have the following JSON

{
"FOO": {
    "id": "23432423",
    "Result": {
        "Status": "SUCCESS",
        "Reason": ""
    }
},
"BAR": {
    "id": "45345535",
    "Result": {
        "Status": "FAILURE",
        "Reason": ""
    }
},
"BAZ": {
    "id": "123432423",
    "Result": {
        "Status": "SUCCESS",
        "Reason": ""
          }
       }
    }

Using jq I wanted the original object format back filtering on status FAILED

Result:

"BAR": {
    "id": "45345535",
    "Result": {
        "Status": "FAILURE",
        "Reason": ""
    }
}

I tried both solutions suggested from above post to_entries | map(select(.value.Status=="FAILURE")) | from_entries and 'with_entries(select(.value.Status =="FAILURE"))' both are giving empty results. Going round and round. Any help apprecaited

Upvotes: 1

Views: 780

Answers (1)

knittl
knittl

Reputation: 265131

Your Status property is nested inside a Result object, but you are selecting Status directly. You must select on .value.Result.Status:

with_entries(select(.value.Result.Status == "FAIL"))

map_values is a bit shorter even:

map_values(select(.Result.Status == "FAIL"))

Output:

{
  "BAR": {
    "id": "x....4",
    "Result": {
      "Status": "FAIL",
      "Reason": ""
    }
  }
}

Upvotes: 2

Related Questions