使用jq对json文件进行排序和过滤 [英] Sorting and filtering a json file using jq
问题描述
我正在尝试解析json文件,以便为工件实例创建删除列表.
I'm trying to parse a json file in order to create a deletion list for an artifactory instance.
我想按两个字段对它们进行分组:repo和path.然后,将每个分组的两个对象保留为最新的修改后"时间戳,并删除json文件中的所有其他对象.
I'd like group them by two fields: repo and path. And then keep the two objects for each grouping with the most recent "modified" timestamp and delete all the other objects in the json file.
因此,原始文件如下所示:
So, an original file that looks like this:
{
"results": [
{
"repo": "repo1",
"path": "docker_image_dynamic",
"size": 3624,
"modified": "2016-10-01T06:22:16.335Z"
},
{
"repo": "repo1",
"path": "docker_image_dynamic",
"size": 3646,
"modified": "2016-10-01T07:03:58.465Z"
},
{
"repo": "repo1",
"path": "docker_image_dynamic",
"size": 3646,
"modified": "2016-10-01T07:06:36.522Z"
},
{
"repo": "repo2",
"path": "docker_image_static",
"size": 3624,
"modified": "2016-09-29T20:31:44.054Z"
}
]
}
应该变成这样:
{
"results": [
{
"repo": "repo1",
"path": "docker_image_dynamic",
"size": 3646,
"modified": "2016-10-01T07:03:58.465Z"
},
{
"repo": "repo1",
"path": "docker_image_dynamic",
"size": 3646,
"modified": "2016-10-01T07:06:36.522Z"
},
{
"repo": "repo2",
"path": "docker_image_static",
"size": 3624,
"modified": "2016-09-29T20:31:44.054Z"
}
]
}
推荐答案
这应该做到:
.results |= [group_by({repo,path})[] | sort_by(.modified)[-2:][]]
按repo
和path
对数组中的项目进行分组后,可以按modified
对组进行排序,并保留已排序组的最后两项.然后将这些组再次拆分,并将它们收集到一个新的数组中.
After grouping the items in the array by repo
and path
, you sort the groups by modified
and keep the last two items of the sorted group. Then split the groups up again and collect them into a new array.
这篇关于使用jq对json文件进行排序和过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!