1

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"?

1
  • 1
    Take care that your manual edition of your JSON made it invalid. Commented Aug 8, 2021 at 21:02

1 Answer 1

1

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"
            }
         ]
      }
   ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

its working in the Jmespath Tester but in my ansible code it just return empty string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.