Reputation: 2146
How can I express a case insensitive simple key reference in jq?
E.g., I can have:
{
"key" : "value"
}
or
{
"kEy" : "value"
}
but not
{
"key" : "value",
"kEy" : "value"
}
Is there a way to express the .key
filter such that it'll catch "key"
or "kEy"
?
Upvotes: 2
Views: 496
Reputation: 85825
One way would be to convert all keys to lower-case as a default format and extract the key name of your choice (inspired from this peak's answer)
with_entries( .key |= ascii_downcase ).key
The .key
inside with_entries(..)
is not to be confused with the key name of your choice, because that is the default name for all key-names when using the family of *entries functions in jq
- with_entries
, to_entries
and from_entries
If your keys are nested inside other objects, one would would be walk
through the entire JSON to recursively rename the keys and fetch the field of your choice
def recursive_key_rename:
walk( if type == "object" then with_entries( .key |= ascii_downcase ) else . end);
recursive_key_rename | .key.anotherkey
See jq-play demo
Upvotes: 3
Reputation: 50795
Given i
flag, the test
builtin matches case-insensitively, you can use it in conjunction with to_entries
. E.g.:
to_entries[] | select(.key | test("key"; "i")) .value
Upvotes: 4