Get last N elements for each item of a JSON object

送分小仙女□ 提交于 2021-01-29 04:43:20

问题


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

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