sort keys in arbitrary order

蓝咒 提交于 2020-04-16 08:34:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!