
概述
JMES是一個增強型的JSON查詢計算語言, 不僅可以用于對JSON資料進行抽取, 還可以做計算與轉換。關于JMES的文法詳細介紹可以參考
JMES Tutorial。
資料加工中的json_select函數和e_json函數支援以JMES文法對(字段或表達式表示JSON的)值提取或計算特定值。其用法為
json_select(字段, "jmes表達式", default=None, restrict=False)
e_json(字段, jmes="jmes表達式", ...)
關于這兩個函數的具體用法,可參考
json_select函數和
e_json函數本文介紹JMES常用文法。
通過key來擷取值
原始日志
"json_data":{
"a": "foo",
"b": "bar",
"c": "baz"
}
jmes文法
json_select(v("json_data"), "a") #傳回值 foo
json_select(v("json_data"), "b") #傳回值 bar
json_select(v("json_data"), "c") # 傳回值 baz
通過層級通路來擷取值
"json_data":{"a":
{"b":
{"c":
{"d":"value"}
}
}
}
json_select(v("json_data"), "a.b.c.d") # 傳回值 value
通過索引來擷取值
通過索引通路主要用于json中的數組資料
"json_data":{
"a": ["b", "c", "d", "e", "f"]
}
json_select(v("json_data"), "a[2]") # 傳回值 d
通過切片操作擷取值
對于json中的數組資料還可以使用切片操作
"json_data":{
"a": ["b", "c", "d", "e", "f"]
}
json_select(v("json_data"), "a[2: ]") # 傳回值 ["d", "e", "f"]
多種用法綜合使用
"json_data":{
"a": {
"b": {
"c": [{"d": [0, [1, 2]]}, {"d": [3, 4]}]
}
}
}
json_select(v("json_data"), "a.b.c[0].d[1][0]") # 傳回值 1
通過投影來擷取值
原始日志1
"json_data":{
"people": [
{"first": "James", "last": "d"},
{"first": "Jacob", "last": "e"},
{"first": "Jayden", "last": "f"},
{"missing": "different"}
],
"foo": {"bar": "baz"}
}
json_select(v("json_data"), "people[*].first") # 傳回值 ["James","Jacob","Jayden"]
原始日志2
"json_data":{
"ops": {
"functionA": {"numArgs": 2},
"functionB": {"numArgs": 3},
"functionC": {"variadic": true}
}
}
json_select(v("json_data"), "ops.*.numArgs") # 傳回值 [2, 3]
原始日志3
"json_data":{
"machines": [
{"name": "a", "state": "running"},
{"name": "b", "state": "stopped"},
{"name": "c", "state": "running"}
]
}
json_select(v("json_data"), "machines[?state=='running'].name") # 傳回值 ["a", "c"]
多值選取
"json_data":{
"people": [
{
"name": "a",
"state": {"name": "up"}
},
{
"name": "b",
"state": {"name": "down"}
}
]
}
json_select(v("json_data"), "people[].[name, state.name]") # 傳回值[["a","up"],["b","down"]]
計算數組長度
對于json中的數組資料,jmes文法支援數組長度的計算
"json_data":{
"a": ["b", "c", "d", "e", "f"]
}
json_select(v("json_data"), "length(a)") # 傳回值 5
# length(a) > 0, 設定"no-empty"字段為true
e_if(json_select(v("json_data"), "length(a)", default=0), e_set("no-empty", true))
更多關于JMES的文法參考
進一步參考
歡迎掃碼加入官方釘釘群獲得實時更新與阿裡雲工程師的及時直接的支援: