How do I turn it over here? Flat projection?
A, Flatten Projections
1. The core 1
This can be ignored for now, but an important kernel is that for list/object projections, the structure of the original document is retained when the projection is created within the projection.
In English, as in the following example. As you can see, the Reservations list contains dictionaries, and the Value of Instances is a list. Reservations [*].instances[*].state Will elements in the original list be disassembled and reassembled into the result list?
import jmespath
dic_1 = {
"reservations": [
{
"instances": [
{"state": "running"},
{"state": "stopped"}
]
},
{
"instances": [
{"state": "terminated"},
{"state": "running"}
]
}
]
}
path = jmespath.search("reservations[*].instances[*].state", dic_1)
print(path)
Copy the code
If you run this command, you can see whether the result list is a list or a list:
D:\Daily\whatisyeild>python jmespath_demo.py
[['running', 'stopped'], ['terminated', 'running']]
Copy the code
Back to Reservations [*]. Instances [*], the outermost [] of reservations[*] was created. Each internal instance instances[*] will also create their own projection list, so the outermost [] in the result contains two child elements [].
Core 2. 2
And if that’s what I’m gonna do['running', 'stopped', 'terminated', 'running']
What do we do with this list?
This is the other core of the Flatten Projections. According to core 1 above, if only the outermost [] is kept, then the inner instances don’t need to be initialized anymore, so try dropping *.
dic_1 = { "reservations": [ { "instances": [ {"state": "running"}, {"state": "stopped"} ] }, { "instances": [ {"state": "terminated"}, {"state": "running"} ] } ] } path = jmespath.search("reservations[*].instances[].state", D:\Daily\whatisyeild>python jmespath_demo.py ['running', 'stopped', 'terminated', 'running']Copy the code
The result is [‘running’, ‘stopped’, ‘terminated’, ‘running’].
To sum up its two characteristics:
- It flattens the child list into the parent list (not recursive, just one level).
- It will create a projection, and anything to the right will be projected onto the newly created list.
For example, if you have a nested list, use [*] to look at the original list structure:
import jmespath dic_1 = [ [0, 1], 2, [3], 4, [5, [6, 7]] ] path = jmespath.search("[*]", D: Daily\whatisyeild>python jmespath_demo.py [[0, 1], 2, [3], 4, [5, [6, 7]]Copy the code
The result is the [[0, 1], 2, [3], 4, [5, [6, 7]]], this time with [] try a list:
import jmespath dic_1 = [ [0, 1], 2, [3], 4, [5, [6, 7]] ] path = jmespath.search("[]", D:\Daily\whatisyeild>python jmespath_demo.py [0, 1, 2, 3, 4, 5, [6, 7]]Copy the code
As you can see, the list is successfully expanded, [0, 1, 2, 3, 4, 5, [6, 7]], not recursively expanded, but sibling. The sublist [6, 7] is sibling to the rest of the list.