Search code examples
selectjqcontainment

jq select and contains error: null (null) and string ("randomtext1") cannot have their containment checked


command:

cat test.json | jq -r '.[] | select(.["$link"] | contains("randomtext1")).id'

I was expecting to have both ids (a and b) show up as result of the above command since they both contains "randomtext1" text under

"input"|"obj1"|"$link" and "input"|"obj3"|"$link". 
jq: error (at <stdin>:11): null (null) and string ("randomtext1") cannot have their containment checked
parse error: Expected value before ',' at line 11, column 2

I see that the "$link" object is within the "input" and "obj#" objects. How do I specify them or do I need to? The error message seems to be pointing to something else. Also only the "input" and "$link" are constant among the records, the name of the "obj#" can change which makes them random.

The test.json file:

[{
      "input": {
            "obj1": {
                "$link": "randomtext1"
            }, 
            "obj2": {
                "$link": "randomtext2"
            }
      },
      "id": "a"
},
{
      "input": {
            "obj3": {
                "$link": "randomtext1"
            }, 
            "obj4": {
                "$link": "randomtext3"
            }
      },
      "id": "b"
}]

Solution

  • The filter:

    .[]
    | select(.input[] | .["$link"] | contains("randomtext1")) 
    | .id
    

    produces:

    "a"
    "b"
    

    Note, however, that contains has very complex semantics, so it would probably be better to use index instead.