使用JQ选择后,JQ编辑文件到位



用JQ Intphere编辑JQ Intploy,例如sed中的-i,我找到了许多解决方案,例如

jq ... input.json > tmp.json && mv tmp.json input.json

这有效,但是我需要过滤我的文件,添加一些数据,然后将其放回原始内容中。(即更新文件中的特定对象(

我的文件包含具有不同Element 的1000多个对象。我将始终在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字段中并保存到文件

将相同的逻辑应用于Inplote将IBM字段编辑为包含"objectName": "contacts"

的对象的"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": ""
}

似乎在使用选择后,我再也无法使用提供的解决方案https://github.com/stedolan/jq/wiki/faq#general-questions

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

此JQ过滤器应执行您想要的事情:

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

至于覆盖文件,许多人都可以访问sponge(CLI UTITIOL的Moreutils Collection的一部分(使用它,例如。

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

相关内容

  • 没有找到相关文章

最新更新