【问题标题】:select elements of an array and update it in-place选择数组的元素并就地更新它
【发布时间】:2020-03-07 14:56:41
【问题描述】:

鉴于以下 JSON,

我正在尝试过滤汽车数组中的项目,其中项目的 cmets 数组为空:

.cars[] |  select(.comments == null)

或者项目的 cmets 数组存在并且任何 cmets 对象不包含值“FooBar”

.cars[] |  select( select(.comments != null) | (any(.comments[]; index("FooBar")) | not) )

同时保留原始结构。

使用 jq,我可以弄清楚如何创建我想要过滤的标准,但我无法理解如何将其应用于顶级项目。

JSON 输入:

{
    "person": {
        "first_name": "Bob",
        "last_name": "Smith"
    },
    "addresses": [
        {
            "home": {
                "line1": "123",
                "line2": "A st."
            }
        },
        {
            "work": {
                "line1": "456",
                "line2": "B st."
            }
        }
    ],
    "cars": [
        {
            "make": "Honda",
            "model": "Civic"
        },
        {
            "make": "Honda",
            "model": "Accord"
        },
        {
            "make": "Honda",
            "model": "Pilot",
            "comments": [
                "Comment 1",
                "Comment 2",
                "FooBar"
            ]
        },
        {
            "make": "Honda",
            "model": "Passport",
            "comments": [
                "Comment 3",
                "Comment 4"
            ]
        }
    ]
}

JSON 输出,与输入相同,但注释数组中包含值“FooBar”的对象被过滤掉:

{
    "person": {
        "first_name": "Bob",
        "last_name": "Smith"
    },
    "addresses": [
        {
            "home": {
                "line1": "123",
                "line2": "A st."
            }
        },
        {
            "work": {
                "line1": "456",
                "line2": "B st."
            }
        }
    ],
    "cars": [
        {
            "make": "Honda",
            "model": "Civic"
        },
        {
            "make": "Honda",
            "model": "Accord"
        },
        {
            "make": "Honda",
            "model": "Passport",
            "comments": [
                "Comment 3",
                "Comment 4"
            ]
        }
    ]
}

【问题讨论】:

    标签: json jq


    【解决方案1】:

    只需使用 update-assignment 运算符 (|=)。

    .cars |= map(select(.comments))
    
    .cars |= map(select(.comments and any(.comments[]; index("FooBar")) | not))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-06
      • 2012-05-19
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      相关资源
      最近更新 更多