使用JQ Select后,JQ编辑文件到位

时间:2018-02-20 04:45:02

标签: json bash filtering jq edit-in-place

用sed中的-i等JQ来编辑json文件我找到了许多解决方案,比如

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字段并保存到文件

将相同的逻辑应用到就地编辑包含"Y"的对象上的"objectName": "contacts"的IBM字段

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

1 个答案:

答案 0 :(得分:3)

由于select选择,您的jq过滤器不是您需要的过滤器。也就是说,它会过滤掉与选择标准不匹配的对象。

这个jq过滤器可以做你想要的:

if (.objectName == "contacts") then .IBM = "Y" else . end

至于覆盖文件,许多有权访问sponge的人使用它,例如

jq 'if (.objectName == "contacts") then .IBM = "Y" else . end' input.json |
  sponge input.json