使用 JQ Select 后 JQ 编辑文件到位
Posted
技术标签:
【中文标题】使用 JQ Select 后 JQ 编辑文件到位【英文标题】:JQ edit file in place after using JQ Select 【发布时间】: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 我知道这些问题有诀窍 【参考方案1】:您的 jq 过滤器不是您需要的,因为 select
选择。即过滤掉不符合选择条件的对象。
这个 jq 过滤器应该做你想做的事:
if (.objectName == "contacts") then .IBM = "Y" else . end
至于覆盖文件,许多有权访问sponge
(CLI 实用程序moreutils 集合的一部分)的人都会使用它,例如
jq 'if (.objectName == "contacts") then .IBM = "Y" else . end' input.json |
sponge input.json
【讨论】:
以上是关于使用 JQ Select 后 JQ 编辑文件到位的主要内容,如果未能解决你的问题,请参考以下文章