【问题标题】:Conditional if/then/else for JMESPath?JMESPath 的条件 if/then/else?
【发布时间】:2020-10-11 20:23:13
【问题描述】:

我正在尝试使用 JMESPath 做一个简单的 if/then/else

例如:'如果输入是字符串,则返回字符串,否则返回输入的“值”属性'。 "abc" 的输入将返回 "abc"{"value":"def"} 的输入将返回 "def"

有了jq,这很容易:if .|type == "string" then . else .value end

使用JMESPath,我可以得到类型

type(@)

或输入:

@

value 属性:

value

但我还没有找到将它们组合成 if-then-else 的方法。有没有办法做到这一点?

【问题讨论】:

    标签: jq jmespath


    【解决方案1】:

    这是可能的,但不是干净的。一般形式为:

    1. 将要测试的值设为数组(用方括号括起来)
    2. 应用 map 函数将过滤后的数组映射到您想要的值(如果为真)
    3. 此时,如果数组过滤器通过,则您有一个数组,其中填充一个(真)项,否则为空
    4. 将该数组连接到一项(错误值)
    5. 最后,在此数组中的索引 0 处获取项目 - 这将是条件的结果

    这应该让您还可以推导出假条件和真条件的可能转换

    例如,如果测试数据是这样的:

    {
       "test": 11
    }
    

    根据您可以得到的值产生结果(以测试数据 11 和 2 为例):

    • "是的,值是11,大于10"
    • "No 值是小于等于 10 的 2"

    像这样:

    [
        map(
            &join(' ', ['Yes, the value is', to_string(@), 'which is greater than 10']), 
            [test][? @ > `10`]
        ), 
        join(' ', ['No the value is', to_string(test), ' which is less than or equal to 10'])
    ][] | @[0]
    

    所以要抽象一个模板:

    [
        map(
            &<True Expression Here>, 
            [<Expression you are testing>][? @ <Test Expression>]
        ), 
        <False Expression Here>)
    ][] | @[0]
    

    【讨论】:

      【解决方案2】:

      人[?general.id !=100] ||人

      {
        "people": [
          {
            "general": {
              "id": 100,
              "age": 20,
              "other": "foo",
              "name": "Bob"
            },
            "history": {
              "first_login": "2014-01-01",
              "last_login": "2014-01-02"
            }
          },
          {
            "general": {
              "id": 101,
              "age": 30,
              "other": "bar",
              "name": "Bill"
            },
            "history": {
              "first_login": "2014-05-01",
              "last_login": "2014-05-02"
            }
          }
        ]
      }
      

      如果其他条件在这里有效

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 2023-03-22
        • 2012-11-25
        • 1970-01-01
        • 1970-01-01
        • 2014-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多