Home > Net >  jq if value contains then append
jq if value contains then append

Time:06-02

This might not be the ideal way to approach this but I am working on bulk update of some Grafana dashboards. When the expr key contains value that includes something like "sum((rate" I want to append to the value another string. Is this even possible?

 if (.dashboard.panels[].targets[].expr | contains("sum((rate")) then .  = "TEST" end'

I've tried a few variations of then action and even removed the concatanation to see if I could get simple replace. But getting

jq: error: syntax error, unexpected end (Unix shell quoting issues?) at <top-level>, line 1:

CodePudding user response:

You should be able to update-assign part of your objects:

.dashboard.panels[].targets[].expr |= if contains("sum((rate") then .   "TEST" else . end

It's also possible to do without the if conditional, by first selecting all the interesting paths and then modifying only them:

(.dashboard.panels[].targets[].expr | select(contains("sum((rate")))  = "TEST"

CodePudding user response:

You always need an else branch. For readability you can also pull the target up front (otherwise . will match the previous context).

.dashboard.panels[].targets[].expr |=
  if contains("sum((rate") then .   "TEST" else . end

Demo

.dashboard.panels[].targets[].expr |= .  
  if contains("sum((rate") then "TEST" else "" end

Demo

  • Related