如何使用JQ有条件地选择值

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

我尝试选择 1 个价格(如果存在),否则我想选择一个始终存在的“默认”价格。如果 RMP 价格不存在,我的 JQ 就会起作用,我只会返回 1 值。但正如您所看到的,如果 RMP 存在,我最终会得到 2 个条目……每个价格一个。我只寻找 1 个结果。它将具有 RMP 价格(如果存在),或者具有 RET 价格。不知道我在这里做错了什么。

JSON

[
  {
    "PartNumber": "ABC123",
    "Prices": {
      "Pricing": [
        {
          "@PriceType": "RET",
          "Price": {
            "#text": "230.3800"
          }
        },
        {
          "@PriceType": "LST",
          "Price": {
            "#text": "230.3800"
          }
        },
        {
          "@PriceType": "RMP",
          "Price": {
            "#text": "152.0000"
          }
        }
      ]
    }
  }
]

JQ

[.[] | {
    sku: .PartNumber,
    price: (.Prices?.Pricing? | if type == "array" then .[] else . end | if any(.; ."@PriceType" == "RMP") then select(."@PriceType"? == "RMP").Price."#text" else select(."@PriceType"? == "RET").Price."#text" end),
}]

结果

[
  {
    "sku": "ABC123",
    "price": "230.3800"
  },
  {
    "sku": "ABC123",
    "price": "152.0000"
  }
]
json jq
1个回答
0
投票

您可以使用

INDEX
将数组转换为对象,然后使用替代运算符
//
选择默认值(如果前一个返回 null):

map({
  sku: .PartNumber,
  price: (.Prices.Pricing | INDEX(."@PriceType") | .RMP // .RET | .Price."#text")
})
[
  {
    "sku": "ABC123",
    "price": "152.0000"
  }
]

演示

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