How to jmespath.search a dictionary key using starts_with
Asked Answered
A

1

4

I have a dictionary, I want to do a nested jmespath.search on the keys of the dictionary for keys that start with a specific string, but I can only seem to use the @ operator once.

> d = {'foo1': 'bar', 'foo2' : 'baz'}  # here's a dummy example

> jmespath.search('keys(@)[?starts_with(@, "foo")]', jmespath.search('@', d))  # in an ideal world, I'd get ['foo1', 'foo2']



> *** jmespath.exceptions.JMESPathTypeError: In function starts_with(), invalid type for value: None, expected one of: ['string'], received: "null" 

This is what I actually get, however when I enter the following:

> jmespath.search('keys(@)[?starts_with([@], "foo")]', jmespath.search('@', d))  # in an ideal world, I'd get ['foo1', 'foo2'] 

I see

> *** jmespath.exceptions.JMESPathTypeError: In function starts_with(), invalid type for value: ['foo1'], expected one of: ['string'], received: "array"

Is there a way of doing this in JMESPath, or am I dreaming? I need the nested bit

Auriol answered 29/1, 2019 at 23:59 Comment(0)
A
4

Annoyingly, the answer is that the single quotes and double quotes in the query need to be switched...

jmespath.search("keys(@)[?starts_with(@, 'foo')]", jmespath.search('@', d))

works.

Auriol answered 30/1, 2019 at 0:33 Comment(1)
too annoying :<Neomaneomah

© 2022 - 2024 — McMap. All rights reserved.