Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return objects in list that the first name starts with a certain value (jmespath)

I am trying to filter through this list of objects and only return the objects where the firstName starts with a specific value.

[
  {"firstName":"Paul","lastName":"Collins"},
  {"firstName":"Jerry","lastName":"Johnson"},
  {"firstName":"Jody","lastName":"Johnson","occupation":"Occupado","company":"Companio"},
  {"firstName":"Paul","lastName":"Johanson","occupation":"Developer","company":"Developer Co"}
]

The farthest I’ve gotten is this:

([].firstName | [?starts_with(@,'J') == `true`])

Which returns:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  "Jerry",
  "Jody"
]

However, I want to return whole objects that fit this condition, not just the firstName field. My desired output would be:

[
  {"firstName":"Jerry","lastName":"Johnson"},
  {"firstName":"Jody","lastName":"Johnson","occupation":"Occupado","company":"Companio"},
]

I couldn’t find a way to pass an array of strings to starts_with. I could get the values from the return and interpolate them into multiple queries one query with a bunch of "|| firstName == name1 || firstName == name2". However I am wanting to try to do this in one query string.

Any ideas?

>Solution :

In JMESPath, if that’s what you are looking for, the filter projection can be applied on any property of an array, by simply specifying the said properties in the brackets selecting the array itself.

So, rather than going [].firstName, the property comes inside the brackets, e.g. [?firstName == 'Jerry'], would give you the whole object of the person named Jerry.

Then you can apply this using start_with():

[?starts_with(firstName,'J')]

Which will yield the expected

[
  {
    "firstName": "Jerry",
    "lastName": "Johnson"
  },
  {
    "firstName": "Jody",
    "lastName": "Johnson",
    "occupation": "Occupado",
    "company": "Companio"
  }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading