我有一個簡單的JSON數組:值增加鍵陣列JQ
[
"smoke-tests",
"other-tests"
]
我想轉換成一個簡單的JSON:
{"smoke-tests": true,
"other-tests": true
}
我試過幾個例子JQ ,但似乎沒有人做我想要的。
jq '.[] | walk(.key = true)'
產生編譯錯誤。
我有一個簡單的JSON數組:值增加鍵陣列JQ
[
"smoke-tests",
"other-tests"
]
我想轉換成一個簡單的JSON:
{"smoke-tests": true,
"other-tests": true
}
我試過幾個例子JQ ,但似乎沒有人做我想要的。
jq '.[] | walk(.key = true)'
產生編譯錯誤。
如果你喜歡的reduce
效率,但不希望使用reduce
明確:
. as $in | {} | .[$in[]] = true
隨着reduce()
功能:
jq 'reduce .[] as $k ({}; .[$k]=true)' file
輸出:
{
"smoke-tests": true,
"other-tests": true
}
$ s='["smoke-tests", "other-tests"]'
$ jq '[.[] | {(.): true}] | add' <<<"$s"
{
"smoke-tests": true,
"other-tests": true
}
打破如何工作的:.[] | {(.): true}
每個項轉換爲對應的字典的值(作爲密鑰)到true
。在[ ]
的周圍意味着我們生成這樣的對象的列表;發送到add
將它們組合成一個單一的對象。
下面是使用添加一個解決方案。它接近於Charles的解決方案,但使用Object construction的行爲來隱式返回多個對象,當它與一個返回多個結果的表達式一起使用時。
[{(.[]):true}]|add
謝謝,@peak;優雅而簡單。 – AG6HQ