如何用JQ实现条件价格选择?优先选RMP,无则选RET
问题:JQ脚本返回重复结果,需实现价格优先级选择
需求:优先选择RMP类型的价格,若不存在则选择默认的RET价格。当前脚本在RMP存在时会返回两个结果(同时包含RET和RMP价格),不符合预期。
示例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" } ]
问题原因
原脚本中使用.[]遍历了Pricing数组的每个元素,并且对每个元素都执行了价格判断逻辑。当RMP存在时,遍历过程中会同时匹配到RET和RMP元素,最终生成两个独立的对象,导致结果重复。
修正后的JQ脚本
[.[] | { sku: .PartNumber, price: ( .Prices?.Pricing? | if type == "array" then ( .[] | select(."@PriceType" == "RMP") ) // ( .[] | select(."@PriceType" == "RET") ) else ( select(."@PriceType" == "RMP") // select(."@PriceType" == "RET") ) end | .Price."#text" ) }]
如果可以确定Pricing始终是数组,还可以用更简洁的写法:
[.[] | { sku: .PartNumber, price: ( .Prices.Pricing | (map(select(."@PriceType" == "RMP"))[0] // map(select(."@PriceType" == "RET"))[0]) | .Price."#text" ) }]
正确结果
[ { "sku": "ABC123", "price": "152.0000" } ]
当RMP不存在时,脚本会自动返回RET价格,完全符合需求。
内容的提问来源于stack exchange,提问作者slapyo
相关产品推荐
相关产品推荐

