获取JSON对象的每个项目的最后N个元素 [英] Get last N elements for each item of a JSON object
本文介绍了获取JSON对象的每个项目的最后N个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用jq给出以下JSON对象,如何获取每个项目的最后两个元素?
Given the following JSON object, using jq, how to get the last two elements for each item?
我一直试图在jqplay.org的帮助下找到解决方案,但没有解决.从具有一致的键名的对象中获取值非常简单,但我无法解决这个问题.
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.
输入:
{
"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" }
}
/* ... */
}
预期结果:
{
"foo": {
"efg": { "key1": "value1" },
"fgh": { "key1": "value1" }
},
"bar": {
"ghi": { "key1": "value1" }
},
"qux": {
"jkl": { "key1": "value1" },
"klm": { "key1": "value1" }
}
/* ... */
}
推荐答案
一个选项是使用delpaths
删除除最后一个N(此处为2)之外的所有字段.但是,您需要将键名转换为路径表示形式.例如:
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([.])))
请参见 jqplay演示.
这篇关于获取JSON对象的每个项目的最后N个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文