问题
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
And the input JSON looks like this:
{
"alma": 1,
"beka": 2,
"paprika": 3,
"korte": 4
}
(jq play link)
While this works, I have more than 10 keys and the add_property_prefix
function is really bloaty because of this.
The question: is there a way to make sorting list less redundant?
I was thinking of some kind of map, but I don't know jq that much to figure out a more elegant solution.
回答1:
To specify the keys and their order:
{ beka, alma, paprika, korte }
Caveat
This only works for keys with "ordinary" names. For example, since end
is a jq keyword, you would have to write:
{ "end": .end}
for a key named "end", at least using extant versions of jq.
来源:https://stackoverflow.com/questions/60886010/sort-keys-in-arbitrary-order