Floyd
Floyd

Reputation: 363

jq unsensitive case key filter

From this "test.json" file :

{
  "key1": "abc",
  "key2": "def",
  "key3": "ghi"
}

I can update "key2" value with the following command :

jq '.key2="123"' test.json

But, is there a way to use the key filter with case unsensitive and make this command works :

jq '.KeY2="123"' test.json

And also... to do nothing if the key was not found in the JSON file. The default behavior is to append the searched key.

Upvotes: 1

Views: 1161

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295687

test(regex; "i") can be used to perform a case-insensitive regular expression match in jq. Thus:

jq --arg key KeY2 --arg newValue 123 '
  [to_entries[] |
   if .key | test($key; "i") then
     .value = $newValue
   else . end
  ] | from_entries' <test.json

That said, being as this is a regex match, you might want to think about how your key name behaves as a regex -- anchoring, etc. An alternative is to convert both versions to lowercase for the comparison only:

jq --arg key KeY2 --arg newValue 123 '
  ($key | ascii_downcase) as $lower_key |
  [to_entries[] |
   if (.key | ascii_downcase) == $lower_key then
     .value = $newValue
   else . end
  ] | from_entries' <test.json

Upvotes: 5

choroba
choroba

Reputation: 242083

You can use ascii_downcase to get the lowercase version of the key:

jq --arg k Key1 '(.[$k | ascii_downcase] // empty) = "123"'

The // empty part prevents the creation of the key.

Upvotes: 2

Related Questions