Changing nested json conditionally using jq

I would like to change something like the following JSON:

{
  "foobar": {
    "a": {
      "adkjfe": {
        "A": 1,
        "foo": "bar"
      }
    },
    "b": {
      "ekjaei": {
        "A": 2,
        "bar": "foo"
      }
    }
  }
}

to add more data, tell {"baz": ["bing", "bop"]}parent A if A = 1. Assuming I don't know the parent key, leaving the rest of json untouched. I have tried many different things, including:

.foobar | .. | .. | .[] | if select(.A==1) then . += {"baz": "bing"} else . end 

which gives me an error and only my modified section.

The result, in this case, which I would like to see:

{
  "foobar": {
    "a": {
      "adkjfe": {
        "A": 1,
        "foo": "bar",
        "baz": ["bing", "bop"]
      }
    },
    "b": {
      "ekjaei": {
        "A": 2,
        "bar": "foo"
      }
    }
  }
}
+4
source share
2 answers

Select only those fields that are of type objectand match your condition ( A == 1):

jq '(.foobar | .. | select(type == "object" and .A == 1)) |= .+ {"baz": ["bing", "bop"]}' test.json

() , ,

+2

, .., , . :

(.foobar[][] | select(.A == 1)) |= .+ {"baz":["bing", "bop"]}
+2

Source: https://habr.com/ru/post/1665164/


All Articles