0

I need to search all dict in a nested array as below by its key with jmespath

my_list = [[{'age': 1, 'name': 'kobe'}, {'age': 2, 'name': 'james'}], [{'age': 3, 'name': 'kobe'}]]

I got an empty list with jmespath search: jmespath.search("[][?name=='kobe']", my_list)

how can I get result: [{'age': 1, 'name': 'kobe'}, {'age': 3, 'name': 'kobe'}] with jmespath search

Enea Dume
  • 3,014
  • 3
  • 21
  • 36
Lucent
  • 23
  • 3

3 Answers3

1

Use the following jmesQuery:

[]|[?name=='kobe']

on input:

[[{"age": 1, "name": "kobe"}, {"age": 2, "name": "james"}], [{"age": 3, "name": "kobe"}]]

to get output:

[
  {
    "age": 1,
    "name": "kobe"
  },
  {
    "age": 3,
    "name": "kobe"
  }
]
Ankit Gupta
  • 275
  • 3
  • 12
0

The problem here is that you have a mix of different types, that is why you don't get expected results.

What you should do is this:

jmespath.search("[].to_array(@)[?name=='kobe'][]", my_list)

Here is a break down using Python console (pay attention to :

>>> my_list
[[{'age': 1, 'name': 'kobe'}, {'age': 2, 'name': 'james'}], [{'age': 3, 'name': 'kobe'}]]

>>> jmespath.search("[]", my_list)
[{'age': 1, 'name': 'kobe'}, {'age': 2, 'name': 'james'}, {'age': 3, 'name': 'kobe'}]

>>> jmespath.search("[].to_array(@)", my_list)
[[{'age': 1, 'name': 'kobe'}], [{'age': 2, 'name': 'james'}], [{'age': 3, 'name': 'kobe'}]]

>>> jmespath.search("[].to_array(@)[]", my_list)
[{'age': 1, 'name': 'kobe'}, {'age': 2, 'name': 'james'}, {'age': 3, 'name': 'kobe'}]

>>> jmespath.search("[].to_array(@)[?name=='kobe']", my_list)
[[{'age': 1, 'name': 'kobe'}], [], [{'age': 3, 'name': 'kobe'}]]

>>> jmespath.search("[].to_array(@)[?name=='kobe'][]", my_list)
[{'age': 1, 'name': 'kobe'}, {'age': 3, 'name': 'kobe'}]

You can find more explanation with examples in this guide: https://www.doaws.pl/blog/2021-12-05-how-to-master-aws-cli-in-15-minutes/how-to-master-aws-cli-in-15-minutes

dapl
  • 39
  • 4
-1

Use Below code:

my_list = [[{'age': 1, 'name': 'kobe'}, {'age': 2, 'name': 'james'}], [{'age': 3, 
'name': 'kobe'}]]

for l in my_list:
    for dictionary in l:
        Value_List = dictionary.values()
        if "kobe" in Value_List:
            print(dictionary)

Output:

{'age': 1, 'name': 'kobe'}
{'age': 3, 'name': 'kobe'}

OR-----

my_list = [[{'age': 1, 'name': 'kobe'}, {'age': 2, 'name': 'james'}], 
          [{'age': 3, 'name': 'kobe'}]]
Match_List = []
for l in my_list:
    for dictionary in l:
        if dictionary["name"] == "kobe":
            Match_List.append(dictionary)
print(Match_List)

Output:

[{'age': 1, 'name': 'kobe'}, {'age': 3, 'name': 'kobe'}]
Anonymous
  • 659
  • 6
  • 16