在測試過程中,經常會取JSON中的某個值,jmespath可以是除了jsonpath的另外一種選擇.
下面通過幾個例子來說明jmespath在python的使用
jmespath python安裝
非常簡單直接pip,
pip install jmespath
查詢一個key值
source={"a": "foo", "b": "bar", "c": "baz"}
result = jmespath.search("a",source)
print(result)
這個的結果為:foo
subexpression
類似於jsonpath,通過.
來表示路徑的層級
source_1={"a": {"b": {"c": {"d": "value"}}}}
sub_result = jmespath.search("a.b.c",source_1)
print(sub_result)
這個例子的結果為:{'d': 'value'}
index expressions
index expression主要使用在數組上
source_2 = ["a", "b", "c", "d", "e", "f"]
index_result = jmespath.search("[1]",source_2)
print(index_result)
這個例子的結果為:b
多個表達式綜合使用
以上幾種表達式可以合起來一期使用:
composite_exp = "a.b.c[0].d[1][0]"
source_3= {"a": {
"b": {
"c": [
{"d": [0, [1, 2]]},
{"d": [3, 4]}
]
}
}}
composite_result = jmespath.search(composite_exp,source_3)
print(composite_result)
這個例子的結果為1
Slicing 切片
slicing 和python本身的slicing比較像,
source_4=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
slicing_exp = "[0:5]"
slicing_result = jmespath.search(slicing_exp,source_4)
print(slicing_result)
這個例子的結果為: [0, 1, 2, 3, 4]
slicing實際上和python自己的機制基本一樣,同樣這個也是主要給數組使用.
有一點需要記住,基本的slicing的格式其實是: [start:stop:step]
Projections
projection不知道怎么翻譯,就先叫做投影吧,具體通過例子來說比較好理解.
projections主要包含一下幾種情況:
- List Projections
- Slice Projections
- Object Projections
- Flatten Projections
- Filter Projections
Projections- 例子
list_exp="people[*].first"
source_5 = {
"people": [
{"first": "James", "last": "d"},
{"first": "Jacob", "last": "e"},
{"first": "Jayden", "last": "f"},
{"missing": "different"}
],
"foo": {"bar": "baz"}
}
proj_result1= jmespath.search(list_exp,source_5)
print(proj_result1) # ['James', 'Jacob', 'Jayden']
obj_exp ="reservations[*].instances[*].state"
source_6= {
"reservations": [
{
"instances": [
{"state": "running"},
{"state": "stopped"}
]
},
{
"instances": [
{"state": "terminated"},
{"state": "runnning"}
]
}
]
}
proj_result2=jmespath.search(obj_exp,source_6)
print(proj_result2) #[['running', 'stopped'], ['terminated', 'runnning']]
# Flatten projections
source_7=[
[0, 1],
2,
[3],
4,
[5, [6, 7]]
]
flat_exp ="[]"
flat_result = jmespath.search(flat_exp,source_7)
print(flat_result) # [0, 1, 2, 3, 4, 5, [6, 7]]
# filter
filter_exp="machines[?state=='running'].name"
filter_source ={
"machines": [
{"name": "a", "state": "running"},
{"name": "b", "state": "stopped"},
{"name":