【发布时间】:2018-07-30 09:17:03
【问题描述】:
在 sed 中使用 JQ 就地编辑 json 文件,例如 -i,我找到了许多解决方案,例如
jq ... input.json > tmp.json && mv tmp.json input.json
这可行,但我需要过滤我的文件,添加一些数据,然后将其放回原始文件。 (即更新文件中的特定对象)
我的文件包含 1000 多个具有不同 Element 的对象。我将始终在Element 上使用过滤器,我为提问而缩短了。我有一个示例文件original.json ...
{
"Element": "acton",
"objectName": "contacts",
"Path": "/contacts",
"Scenario": "",
"serviceLevel": "",
"IBM": "",
"Gap": "",
"clientPhase": "",
"parentPhase": "",
"existsToday": ""
}
{
"Element": "acton",
"objectName": "optouts",
"Path": "/optouts",
"Scenario": "",
"serviceLevel": "",
"IBM": "",
"Dependency": "",
"Gap": "",
"clientPhase": "",
"parentPhase": "",
"existsToday": ""
}
{
"Element": "acton",
"objectName": "subscriptionTypes",
"Path": "/subscription-types",
"Scenario": "",
"serviceLevel": "",
"IBM": "",
"Dependency": "",
"Gap": "",
"clientPhase": "",
"parentPhase": "",
"existsToday": ""
}
我想通过objectName 过滤contacts 将一些数据添加到空IBM 字段并保存到文件中
应用相同的逻辑在包含 "objectName": "contacts" 的对象上将 IBM 字段就地编辑为 "Y"
jq 'select(.objectName == "contacts") | .IBM = "Y"' original.json > tmpjson.json && mv tmpjson.json original.json
现在我的文件original.json 显示
{
"Element": "acton",
"objectName": "contacts",
"Path": "/contacts",
"Scenario": "",
"serviceLevel": "",
"IBM": "Y",
"Dependency": "",
"Gap": "",
"clientPhase": "",
"parentPhase": "",
"existsToday": ""
}
预期结果
{
"Element": "acton",
"objectName": "contacts",
"Path": "/contacts",
"Scenario": "",
"serviceLevel": "",
"IBM": "Y",
"Gap": "",
"clientPhase": "",
"parentPhase": "",
"existsToday": ""
}
{
"Element": "acton",
"objectName": "optouts",
"Path": "/optouts",
"Scenario": "",
"serviceLevel": "",
"IBM": "",
"Dependency": "",
"Gap": "",
"clientPhase": "",
"parentPhase": "",
"existsToday": ""
}
{
"Element": "acton",
"objectName": "subscriptionTypes",
"Path": "/subscription-types",
"Scenario": "",
"serviceLevel": "",
"IBM": "",
"Dependency": "",
"Gap": "",
"clientPhase": "",
"parentPhase": "",
"existsToday": ""
}
使用 select 后,我似乎无法再使用提供的解决方案 https://github.com/stedolan/jq/wiki/FAQ#general-questions
【问题讨论】:
-
@peak 我知道这些问题有诀窍
标签: json bash filtering jq edit-in-place