4

在 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": ""
}

我想过滤以objectNamecontacts一些数据添加到空 IBM 字段并保存到文件中

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

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

4

1 回答 1

16

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

这个 jq 过滤器应该做你想做的事:

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

至于覆盖文件,许多有权访问spongemoreutils CLI 实用程序集合的一部分)的人都使用它,例如

jq 'if (.objectName == "contacts") then .IBM = "Y" else . end' input.json |
  sponge input.json
于 2018-02-20T04:52:06.893 回答