2

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" ?

peak
  • 105,803
  • 17
  • 152
  • 177
Shang Jian Ding
  • 1,931
  • 11
  • 24

2 Answers2

4

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

Online demo

oguz ismail
  • 1
  • 16
  • 47
  • 69
3

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

Inian
  • 80,270
  • 14
  • 142
  • 161
  • Inia, do you know how to make this work if the JSON document has nested keys. e.g instead of simply `.key`, it coul dhave `.key.anotherKey` – Shang Jian Ding Jun 18 '20 at 15:00