本文档主要介绍JMES的常用语法。

JMES是一个增强型的JSON查询计算语言,不仅可以对JSON数据进行提取,还可以做计算与转换。关于JMES语法的详细介绍请参见JMES Tutorial

数据加工中的json_selecte_jsone_split支持通过JMES提取字段或JSON表达式的值,或者通过JMES计算特定的值。其用法为:
json_select(值, "jmes表达式", ...)
e_json(字段名, jmes="jmes表达式", ...)
e_split(字段名, ... jmes="jmes表达式", ...)
函数的具体用法请参见json_selecte_jsone_split

通过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"}
                  }
                }
             }
  • JMES语法
    json_select(v("json_data"), "a.b.c.d") # 返回值 value

通过切片操作获取值

  • 原始日志
    "json_data":{
       "a": ["b", "c", "d", "e", "f"]
     }
  • JMES语法
    json_select(v("json_data"), "a[2: ]") # 返回值 ["d", "e", "f"]

多种用法综合使用

  • 原始日志
    "json_data":{
      "a": {
        "b": {
          "c": [{"d": [0, [1, 2]]}, {"d": [3, 4]}]
        }
      }
    }
  • JMES语法
    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"}
    }
  • JMES语法1
    json_select(v("json_data"), "people[*].first") # 返回值 ["James","Jacob","Jayden"]
  • 原始日志2
    "json_data":{
        "ops": {
        "functionA": {"numArgs": 2},
        "functionB": {"numArgs": 3},
        "functionC": {"variadic": true}
        }
      }
  • JMES语法2
    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"}
      ]
    }
  • JMES语法3
    json_select(v("json_data"), "machines[?state=='running'].name") # 返回值 ["a", "c"]

多值选取

  • 原始日志
    "json_data":{
      "people": [
        {
        "name": "a",
        "state": {"name": "up"}
        },
        {
        "name": "b",
        "state": {"name": "down"}
        }
      ]
    }
  • JMES语法
    json_select(v("json_data"), "people[].[name, state.name]") # 返回值[["a","up"],["b","down"]]

计算数组长度

  • 原始日志
    "json_data":{
       "a": ["b", "c", "d", "e", "f"]
     }
  • JMES语法
    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))