问题
Given the following JSON object, using jq, how to get the last two elements for each item?
I have been trying to find a solution with the help of jqplay.org but didn't get anywhere. While getting values out of objects having consistent key names is rather straightforward, I can't get my head around this.
Input:
{
"foo": {
"abc": { "key1": "value1" },
"bcd": { "key1": "value1" },
"cde": { "key1": "value1" },
"def": { "key1": "value1" },
"efg": { "key1": "value1" },
"fgh": { "key1": "value1" }
},
"bar": {
"ghi": { "key1": "value1" }
},
"qux": {
"hij": { "key1": "value1" },
"ijk": { "key1": "value1" },
"jkl": { "key1": "value1" },
"klm": { "key1": "value1" }
}
/* ... */
}
Expected result:
{
"foo": {
"efg": { "key1": "value1" },
"fgh": { "key1": "value1" }
},
"bar": {
"ghi": { "key1": "value1" }
},
"qux": {
"jkl": { "key1": "value1" },
"klm": { "key1": "value1" }
}
/* ... */
}
回答1:
One option is to delete all fields but the last N (2 here) using delpaths
. You need to convert key names to path representations though. E.g:
map_values(delpaths(keys_unsorted[:-2] | map([.])))
See the jqplay demo.
回答2:
A straightforward and efficient solution:
map_values( to_entries[-2:] | from_entries)
来源:https://stackoverflow.com/questions/58181874/get-last-n-elements-for-each-item-of-a-json-object