jsonjq

Delete all where DOES NOT contain


I have this JSON file json1.json:

{
    "a":"val1",
    "b":"val2",
    "nest1": {
        "z": "x",
        "test": "containval"
    }
}

I need to get a new json where elements whose values that contain val are removed, ANY property can have val, this gets me close:

jq 'del(.. | select(. == "val1"))' .\json1.json

it produces this:

{
  "b": "val2",
  "nest1": {
    "z": "x",
    "test": "containval"
  }
}

Except that it checks for values being EQUAL to val1, and I only need where the value DOES NOT CONTAIN "val".

Desired output:

{
    "a":"val1",
    "b":"val2",
    "nest1": {
        "test": "containval"
    }
}

Solution

  • The solution is simple. Instead of checking for equality, use the filters strings and contains() to select and remove the values that contain "val" (together with their associated keys):

    del(.. | select(strings | contains("val")))
    

    Check it online.