user63898
user63898

Reputation: 30895

jmespath :select json object element based on other (array) element in the object

I have this JSON

{
    "srv_config": [{
             "name": "db1",
             "servers": ["srv1", "srv2"],
             "prop": [{"source":"aa"},"destination":"bb"},{"source":"cc"},"destination":"cc"},]
         }, {
             "name": "db2",
             "servers": ["srv2", "srv2"],
             "prop": [{"source":"dd"},"destination":"dd"},{"source":"ee"},"destination":"ee"},]
         }
     ]
 }

I try to build a JMESPath expression to select the prop application in each object in the main array, but based on the existence of a string in the servers element.

To select all props, I can do:

*.props [*]

But how do I add condition that says "select only if srv1 is in servers list"?

Upvotes: 1

Views: 1151

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39129

You can use the contains function in order to filter based on a array containing something.

Given the query:

*[?contains(servers, `srv1`)].prop | [][]

This gives us:

[
  {
    "source": "aa",
    "destination": "bb"
  },
  {
    "source": "cc",
    "destination": "cc"
  }
]

Please mind that I am also using a bit of flattening here.


All this run towards a corrected version of you JSON:

{
   "srv_config":[
      {
         "name":"db1",
         "servers":[
            "srv1",
            "srv2"
         ],
         "prop":[
            {
               "source":"aa",
               "destination":"bb"
            },
            {
               "source":"cc",
               "destination":"cc"
            }
         ]
      },
      {
         "name":"db2",
         "servers":[
            "srv2",
            "srv2"
         ],
         "prop":[
            {
               "source":"dd",
               "destination":"dd"
            },
            {
               "source":"ee",
               "destination":"ee"
            }
         ]
      }
   ]
}

Upvotes: 1

Related Questions