Venu Reddy
Venu Reddy

Reputation: 49

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

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!

Upvotes: 0

Views: 164

Answers (3)

peak
peak

Reputation: 116690

From your description, it would seem the following would suffice:

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

If you need more than that, then I’d use the above with walk:

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

Upvotes: 2

ikegami
ikegami

Reputation: 385645

( .parent1.parent1key | select( . ) ) |= $parent1keyarg |
( .parent2.parent2key | select( . ) ) |= $parent2keyarg

Upvotes: 1

Inian
Inian

Reputation: 85560

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.

Upvotes: 2

Related Questions