gpt4 book ai didi

jq - 从 JQ 中的稀疏对象数组生成新数组

转载 作者:行者123 更新时间:2023-12-02 09:08:33 31 4
gpt4 key购买 nike

我有一个要用 JQ 处理的 JSON 文件。它在另一个对象中有一个对象数组,带有一个我想用来填充新数组的键。

在我的实际用例中,它嵌套在许多其他的绒毛中,还有更多的数组,但将其作为此类事物的一个更简单但具有代表性的示例:

{
"numbers": [
{
"numeral": 1,
"ordinal": "1st",
"word": "One"
},
{
"numeral": 2,
"ordinal": "2nd",
"word": "Two"
},
{
"numeral": 5,
"ordinal": "5th",
"word": "Five"
},
{
"some-other-fluff-i-want-to-ignore": true
}
]
}

我想用JQ根据元素得到一个新的数组,忽略一些元素并处理缺失的元素。例如

[
"The 1st word is One",
"The 2nd word is Two",
"Wot no number 3?",
"Wot no number 4?",
"The 5th word is Five"
]

在循环中为现有的元素执行此操作非常简单、简洁和优雅:

.numbers | map( . | select( .numeral) | [ "The", .ordinal, "word is", .word ] | join (" "))

但我找不到处理缺失条目的方法。我有一些可以正常工作的代码:

.numbers | [
( .[] | select(.numeral == 1) | ( [ "The", .ordinal, "word is", .word ] | join (" ")) ) // "Wot no number 1?",
( .[] | select(.numeral == 2) | ( [ "The", .ordinal, "word is", .word ] | join (" ")) ) // "Wot no number 2?",
( .[] | select(.numeral == 3) | ( [ "The", .ordinal, "word is", .word ] | join (" ")) ) // "Wot no number 3?",
( .[] | select(.numeral == 4) | ( [ "The", .ordinal, "word is", .word ] | join (" ")) ) // "Wot no number 4?",
( .[] | select(.numeral == 5) | ( [ "The", .ordinal, "word is", .word ] | join (" ")) ) // "Wot no number 5?"
]

它以某种方式产生可用的输出:

richard@sophia:~$ jq -f make-array.jq < numbers.json
[
"The 1st word is One",
"The 2nd word is Two",
"Wot no number 3?",
"Wot no number 4?",
"The 5th word is Five"
]
richard@sophia:~$

然而,虽然它产生输出,处理丢失的元素并忽略我不想要的位,但它显然是非常无用的代码,需要 for 循环或类似的东西,但我看不到办法JQ来做这个。有什么想法吗?

最佳答案

jq解决方案:

jq 'def print(o): "The \(o.ordinal) word is \(o.word)";
.numbers | (reduce map(select(.numeral))[] as $o ({}; .["\($o.numeral)"] = $o)) as $o
| [range(0; ($o | [keys[] | tonumber] | max))
| "\(.+1)" as $i
| if ($o[$i]) then print($o[$i]) else "Wot no number \($i)?" end
]' input.json

输出:

[
"The 1st word is One",
"The 2nd word is Two",
"Wot no number 3?",
"Wot no number 4?",
"The 5th word is Five"
]

关于jq - 从 JQ 中的稀疏对象数组生成新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55198806/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com