首页 > 解决方案 > 如何将函数应用于jq中的多个字段

问题描述

我尝试减小 jq 调用的大小。当前命令是:

jq '.result | .[].newValueJson.action |= (. | tostring // .) | .[].oldValueJson.action |= (. | tostring // .) | .[].metadata.value |= (. | tostring // .)'

如您所见,函数“tostring”以相同的方式应用于“newValueJson.action”、“oldValueJson.action”和“metadata.value”。我想知道是否有更紧凑的语法,所以我只需要应用 tostring 一次?

我提取的样本数据显示了正在做什么(这不是完整的 json 树)。

资源:

{
    "result": [{
            "id": 1,
            "action": {
                "result": true,
                "type": "filter_create"
            },
            "newValueJson": {
                "action": "simulate"
            },
            "oldValueJson": {
                "action": "enforce"
            },
            "metadata": {
                "value": false
            }
        },
        {
            "id": 2,
            "action": {
                "result": true,
                "type": "filter_create"
            },
            "newValueJson": {
                "action": {
                    "mode": "simulate",
                    "timeout": 3600
                }
            },
            "oldValueJson": {
                "action": {
                    "mode": "enforce",
                    "timeout": 3600
                }
            },
            "metadata": {
                "value": "off"
            }
        }
    ]
}

结果:

[{
        "id": 1,
        "action": {
            "result": true,
            "type": "filter_create"
        },
        "newValueJson": {
            "action": "simulate"
        },
        "oldValueJson": {
            "action": "enforce"
        },
        "metadata": {
            "value": "false"
        }
    },
    {
        "id": 2,
        "action": {
            "result": true,
            "type": "filter_create"
        },
        "newValueJson": {
            "action": "{\"mode\":\"simulate\",\"timeout\":3600}"
        },
        "oldValueJson": {
            "action": "{\"mode\":\"enforce\",\"timeout\":3600}"
        },
        "metadata": {
            "value": "off"
        }
    }
]

谢谢和最好的。

标签: jq

解决方案


您可以使用(..)如下方式将操作分组在一起。此外.[],您可以使用数组表示法map(..)来处理应用过滤器表达式,而不是使用result数组表示法

.result | map((.newValueJson.action, .oldValueJson.action, .metadata.value ) |= (. | tostring // .))

推荐阅读