以任意顺序对键进行排序 [英] sort keys in arbitrary order
问题描述
对于副项目,我想使用jq对JSON的键进行排序,并提出以下解决方案:
For a side-project I want to sort the keys of a JSON with jq, and come up with the following solution:
def add_property_prefix:
if .key == "beka" then "01__"+.key
elif .key == "alma" then "02__"+.key
elif .key == "paprika" then "03__"+.key
elif .key == "korte" then "04__"+.key
else .key end
;
def del_property_prefix:
.key | sub("^[0-9]{2}__"; "")
;
to_entries
| map({ key: add_property_prefix, value: .value })
| sort_by(.key)
| map({ key: del_property_prefix, value: .value })
| from_entries
输入的JSON如下所示:
And the input JSON looks like this:
{
"alma": 1,
"beka": 2,
"paprika": 3,
"korte": 4
}
( jq play lin k )
虽然可行,但我有10个以上的键,并且 add_property_prefix
函数确实很有效
While this works, I have more than 10 keys and the add_property_prefix
function is really bloaty because of this.
问题:是否有办法减少排序列表的冗余度?
我在想某种地图,但我不太了解jq以找出更优雅的解决方案。
I was thinking of some kind of map, but I don't know jq that much to figure out a more elegant solution.
推荐答案
指定键及其顺序:
{ beka, alma, paprika, korte }
Caveat
仅适用于带有普通名称。例如,由于 end
是jq关键字,因此您必须编写:
Caveat
This only works for keys with "ordinary" names. For example, since end
is a jq keyword, you would have to write:
{ "end": .end}
至少有一个名为 end的键使用现存的jq版本。
for a key named "end", at least using extant versions of jq.
这篇关于以任意顺序对键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!