You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于嵌套子属性筛选父级对象的jq实现问题

问题

我有一份扫描DVD得到的JSON文档,其中包含TitleList数组,每个元素下有ChapterList数组,其每个元素包含Duration对象。需要筛选出所有嵌套Duration对象均满足条件的TitleList元素的指定属性。

尝试了map()、select()和all()的多种组合但未成功,能进入JSON筛选内容,但无法回到上层获取Index。最接近的尝试代码如下(输出为空):

.TitleList[] | select(.ChapterList[] | all(.Duration.Ticks > 180000)) | .Index

示例JSON:

{
    "TitleList": [
        {
            "Index": 1,
            "ChapterList": [
                {
                    "Name": "Chapter 1",
                    "Duration": {"Ticks": 48367000}
                },
                {
                    "Name": "Chapter 2",
                    "Duration": {"Ticks": 27470000}
                },
                {
                    "Name": "Chapter 3",
                    "Duration": {"Ticks": 97000}
                }
            ]
        },
        {
            "Index": 2,
            "ChapterList": [
                {
                    "Name": "Chapter 1",
                    "Duration": {"Ticks": 62167000}
                },
                {
                    "Name": "Chapter 2",
                    "Duration": {"Ticks": 58281700}
                },
                {
                    "Name": "Chapter 3",
                    "Duration": {"Ticks": 4582000}
                }
            ]
       },
        {
            "Index": 3,
            "ChapterList": [
                {
                    "Name": "Chapter 1",
                    "Duration": {"Ticks": 48367000}
                },
                {
                    "Name": "Chapter 2",
                    "Duration": {"Ticks": 48281000}
                },
                {
                    "Name": "Chapter 3",
                    "Duration": {"Ticks": 38500}
                }
            ]
        }
    ]
}

期望返回TitleList数组中所有Duration.Ticks均大于180000的元素的Index,示例中应仅输出2。

解决方法

你的问题出在select里的表达式逻辑——.ChapterList[] | all(...)会先展开ChapterList的每个元素,再对单个元素用all,这不符合“检查所有章节都满足条件”的需求。正确的做法是直接对整个ChapterList数组使用all。

正确的jq命令:

.TitleList[] | select(.ChapterList | all(.Duration.Ticks > 180000)) | .Index

逻辑说明

  • .ChapterList | all(...):针对当前TitleList元素的整个ChapterList数组,判断其中所有元素的.Duration.Ticks是否都大于180000
  • 满足条件的TitleList元素会被保留,最后提取其.Index属性

用示例JSON测试该命令,会输出:

2

内容的提问来源于stack exchange,提问作者miken32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 01:27:09