JMESPath 的条件 if/then/else?

问题描述 投票:0回答:3

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

例如:“如果输入是字符串,则返回该字符串,否则返回输入的“value”属性”。输入

"abc"
将返回
"abc"
。输入
{"value":"def"}
将返回
"def"

使用

jq
这很简单:
if .|type == "string" then . else .value end

使用 JMESPath,我可以获得类型

type(@)

或输入:

@

value
属性:

value

但我还没有找到一种方法将它们组合成 if-then-else。有什么办法可以做到这一点吗?

jq jmespath
3个回答
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"
      }
    }
  ]
}

if else 条件在这里有效


1
投票

这是可能的,但并不彻底。一般形式为:

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

这应该允许您导出错误和真实条件的可能转换

例如测试数据如下:

{
   "test": 11
}

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

  • “是的,该值为 11,大于 10”
  • “否,值为 2,小于或等于 10”

像这样:

[
    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]

0
投票

输入

{
  "SubscriptionId": 2,
  "CustomerId": 234,
  "ShowContractIn": "Monthly",
  "AnnualCost": 1200.00,
  "MonthlyCost": 100.00 
}

转型

{
  ContractCost: ShowContractIn == 'Monthly' && MonthlyCost || AnnualCost
}

输出

{
  "ContractCost": 100.00
}

取自 在此输入链接描述

© www.soinside.com 2019 - 2024. All rights reserved.