Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq select compare case insensitive

Tags:

bash

shell

jq

I have a json file that looks like the following:

{
    "items": [
        {
            "id": "some_id_1",
            "name": "job_get_re_Log",
            "type": "standard",
            "workspace": {
                "id": "some_id_2",
                "name": "Shared",
                "description": "",
                "type": "custom",
                "environment": {
                    "id": "some_id_3",
                    "name": "DEV"
                }
            }
        }
    ]
}

To get the id (some_id_1), I run the following command:

name="job_get_re_log"
workspace="Shared"
environment="DEV"

id=$(echo $jsonFile | jq -r ".items[] | select(.name == \"$name\" and .workspace.name == \"$workspace\" and .workspace.environment.name == \"$environment\").id")

echo "$id"

As you can see the name variable is "job_get_re_log" but the name in the json is "job_get_re_Log" (capital L). This ends up failing and returning nothing because it's looking for an exact match.

How can I modify the select command so it compares without considering the case (case insensitive)?

like image 967
o.o Avatar asked Jun 09 '26 14:06

o.o


1 Answers

To use test/1 to check for equality ignoring case, you would have to anchor the regex string. Assuming $name has no special regex characters:

jq -r --arg w "$workspace" --arg e "$environment" --arg n "$name" '
  .items[]
  | select( (.name | test("^\($n)$"; "i")) and
            (.workspace.name == $w) and
            (.workspace.environment.name == $e)) 
  | .id'

The point of using test/1 of course is that it handles typographical case outside the ASCII range, e.g.

$ jq 'test("Å";"i")' <<< '"å"'
true

As pointed out by @OguzIsmail, if you wish to use test even if $name might contain regex-special characters, you could use the \Q...\E escape mechanism, as in:

$ jq 'test("\\Q.\\E")' <<< '"a"'
false
like image 86
peak Avatar answered Jun 11 '26 21:06

peak