user3613331
user3613331

Reputation: 121

How to get entire parent node using jq json parser?

I am trying to find a value in the json file and based on that I need to get the entire json data instead of that particular block.

Here is my sample json

[{
      "name" : "Redirect to Website 1",

      "behaviors" : [ {
        "name" : "redirect",
        "options" : {
          "mobileDefaultChoice" : "DEFAULT",
          "destinationProtocol" : "HTTPS",
          "destinationHostname" : "SAME_AS_REQUEST",
          "responseCode" : 302
        }
      } ],
      "criteria" : [ {
        "name" : "requestProtocol",
        "options" : {
          "value" : "HTTP"
        }
      } ],
      "criteriaMustSatisfy" : "all"
},
{
      "name" : "Redirect to Website 2",

      "behaviors" : [ {
        "name" : "redirect",
        "options" : {
          "mobileDefaultChoice" : "DEFAULT",
          "destinationProtocol" : "HTTPS",
          "destinationHostname" : "SAME_AS_REQUEST",
          "responseCode" : 301
        }
      } ],
      "criteria" : [ {
        "name" : "contentType",
        "options" : {
          "matchOperator" : "IS_ONE_OF",
          "values" : [ "text/html*", "text/css*", "application/x-javascript*" ],
        }
      } ],
      "criteriaMustSatisfy" : "all"
}]

I am trying to match for "name" : "redirect" inside each behaviors array and if it matches then I need the entire block including the "criteria" section, as you can see its under same block {}

I managed to find the values using select methods but not able to get the parent section.

https://jqplay.org/s/BWJwVdO3Zv

Any help is much appreciated!

Upvotes: 1

Views: 954

Answers (2)

peak
peak

Reputation: 116780

To avoid unwanted duplication:

.[]
| first(select(.behaviors[].name == "redirect"))

Equivalently:

.[]
| select(any(.behaviors[]; .name == "redirect"))

Upvotes: 1

oliv
oliv

Reputation: 13249

You can try this jq command:

 <file jq 'select(.[].behaviors[].name=="redirect")'

Upvotes: 1

Related Questions