Home > Blockchain >  With JQ search multiple key: value pairs and replace with define variable already
With JQ search multiple key: value pairs and replace with define variable already

Time:07-18

I have a couple of json files and both or one of the keys below, might exist or none exists.

{
  "parent1": {
    "parent1key": "parent1value"
  },
  "parent2": {
    "parent2key": "parent2value"
  }

}

if both the key: pairs always exist, I could use

jq --arg parent1keyarg $MyVAL1 --arg parent2keyarg $MyVAL2 '(..|objects|select(.parent1key ).parent1key ) |= $parent1keyarg | (..|objects|select(.parent2key).parent2key) |= $parent2keyarg ' jsonfile.json

  1. I want to find the parent1key and parent2key and if found one or both, then replace them with a variable that's generated during runtime. If none of the key: values are found just ignore it rather than troughing up an error.

  2. I want to use jq --arg instead of bash if conditions, just to ensure the JSON formatting is accurate ( or jq is interesting to me ).

how could we write conditions in JQ is what I'm unable to figure out from jq manuals.

Appreciate it if anyone could help me with this.

Thanks!

CodePudding user response:

To keep things simple, I’d use walk along the following lines:

walk(if type=="object"
     then if has("parent1key") then .parent1key = $a
          else . end 
          | if has("parent2key") then .parent2key = $b
            else . end
     else . end)

CodePudding user response:

A simple walk/1 expression would be sufficient to check for existence of the key recursively. It can be further improved by making it a function.

def replace(k; v):
   walk(if type == "object" and has(k) then .[k] = v else . end);

replace("parent1key"; "foo") | replace("parent2key"; "bar")

The first argument to replace takes the key name for which the value is to be replaced. Simply pipe any numbers of keys and the associated values that you want to change.

  • Related