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)?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With