这里要怎么翻呢?扁平投影?
一、Flatten Projections
1. 核心1
这个可以暂时忽略,一个重要的核心是:对于列表/对象投影,在投影中创建投影时,原始文档的结构将保留。

说人话就是,比如下面的例子。
可以看到,reservations列表中嵌套了字典,而instances的value,又是一个列表。
这时候,用reservations[*].instances[*].state,那么得到的值又是什么样子的呢?
原来是列表中的元素会被拆散,重新装到结果列表里吗?
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)
运行一下,可以看到结果列表中,原来是列表的还是列表:
D:Dailywhatisyeild>python jmespath_demo.py
[['running', 'stopped'], ['terminated', 'running']]
我们可以再回过来看reservations[*].instances[*],其实最外层的[] 就是 reservations[*]创建的.
而内部的每一个实例instances[*],也会各自再创建出投影列表,所以结果中最外层的[]里包含了2个子元素[]。
2. 核心2
那如果我就是要['running', 'stopped', 'terminated', 'running'] 这个列表要怎么办?

这就是Flatten Projections的另一个核心了,根据上面核心1里说的,如果只要保留最外侧的[],
那么内层的实例就不需要再初始化创建[]了,那么就去掉*试一下。
dic_1 = {
"reservations": [
{
"instances": [
{"state": "running"},
{"state": "stopped"}
]
},
{
"instances": [
{"state": "terminated"},
{"state": "running"}
]
}
]
}
path = jmespath.search("reservations[*].instances[].state", dic_1)
print(path)
#运行结果
D:Dailywhatisyeild>python jmespath_demo.py
['running', 'stopped', 'terminated', 'running']
结果是['running', 'stopped', 'terminated', 'running'] ,搞定。
总结一下它的2个特点:
- 它将子列表展平到父列表中(不是递归的,只是一个级别)。
- 它将创建一个投影,右边的任何内容都将投影到新创建的列表上。
可以试一下,比如下面例子里有个嵌套列表,先来用[*]看一下,原始的列表结构:
import jmespath
dic_1 = [
[0, 1],
2,
[3],
4,
[5, [6, 7]]
]
path = jmespath.search("[*]", dic_1)
print(path)
#运行结果
D:Dailywhatisyeild>python jmespath_demo.py
[[0, 1], 2, [3], 4, [5, [6, 7]]]
结果是[[0, 1], 2, [3], 4, [5, [6, 7]]] ,这时候用[]展开列表试一下:
import jmespath
dic_1 = [
[0, 1],
2,
[3],
4,
[5, [6, 7]]
]
path = jmespath.search("[]", dic_1)
print(path)
#运行结果
D:Dailywhatisyeild>python jmespath_demo.py
[0, 1, 2, 3, 4, 5, [6, 7]]
可以看到,列表成功展开,[0, 1, 2, 3, 4, 5, [6, 7]] ,不是递归展开,只是同级,子列表[6, 7] 与列表其他元素同级。