识别 json 中的项目并更新其中的键和值
identify an item in json and update key and value in it
我的输入json如下,我希望select如果“名称”:“bot-block”然后更新它的 “动作”:到“块”:{}来自“允许”:{},我使用 select 命令执行此操作,但它过滤了我的 json 并且仅 returns 带有 .Name=bot-block 的项目,我想在 [=18] 中更新=] 不过滤。这是我当前的命令 jq '.[] | select(.Name=="bot-block") | .Action |= . + { "Block" : {} } ' input.json
[
{
"Name": "searchblock",
"Priority": 3,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "searchblock"
}
},
{
"Name": "bot-block",
"Priority": 4,
"Action": {
"Allow": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "user-agent"
}
}
]
预期输出
[
{
"Name": "searchblock",
"Priority": 3,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "searchblock"
}
},
{
"Name": "bot-block",
"Priority": 4,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "user-agent"
}
}
]
您可以直接“赋值”到所选数组项的Action
元素。 |=
只影响选中的项,但过滤器的输出仍然是整个输入。
jq 'map(select(.Name=="bot-block").Action |= {Block: {}})' input.json
超级近!这只是一个优先级问题。
.[] | select(.Name=="bot-block") | .Action |= . + { "Block" : {} }
应该是
( .[] | select(.Name=="bot-block") | .Action ) |= . + { "Block" : {} }
因为 |=
的优先级低于 |
。
认为 foo | bar |= baz
有修改 foo | bar
但返回 foo
。因此,原始片段 returns 修改后的 .[] | select(.Name=="bot-block")
,而固定版本 returns 修改后的 .
.
我的输入json如下,我希望select如果“名称”:“bot-block”然后更新它的 “动作”:到“块”:{}来自“允许”:{},我使用 select 命令执行此操作,但它过滤了我的 json 并且仅 returns 带有 .Name=bot-block 的项目,我想在 [=18] 中更新=] 不过滤。这是我当前的命令 jq '.[] | select(.Name=="bot-block") | .Action |= . + { "Block" : {} } ' input.json
[
{
"Name": "searchblock",
"Priority": 3,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "searchblock"
}
},
{
"Name": "bot-block",
"Priority": 4,
"Action": {
"Allow": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "user-agent"
}
}
]
预期输出
[
{
"Name": "searchblock",
"Priority": 3,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "searchblock"
}
},
{
"Name": "bot-block",
"Priority": 4,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "user-agent"
}
}
]
您可以直接“赋值”到所选数组项的Action
元素。 |=
只影响选中的项,但过滤器的输出仍然是整个输入。
jq 'map(select(.Name=="bot-block").Action |= {Block: {}})' input.json
超级近!这只是一个优先级问题。
.[] | select(.Name=="bot-block") | .Action |= . + { "Block" : {} }
应该是
( .[] | select(.Name=="bot-block") | .Action ) |= . + { "Block" : {} }
因为 |=
的优先级低于 |
。
认为 foo | bar |= baz
有修改 foo | bar
但返回 foo
。因此,原始片段 returns 修改后的 .[] | select(.Name=="bot-block")
,而固定版本 returns 修改后的 .
.