Case-insensitive search of an object with jq

107 Views Asked by At

When retrieving an object from an array with jq in a JSON file like this

[
  {
    "field1": "Object1_Value1",
    "field2": "Object1_Value2",
    "field3": "Object1_Value3"
  },
  {
    "field1": "Object2_Value1",
    "field2": "Object2_Value2",
    "field3": "Object2_Value3"
  }
]

that matches a given string, .field1 may include capital letters:

jq --raw-output '.[] | select(.field1 == "object1_value1") | .field2, .field3' filename

How can ascii_downcase be used here to match the string in lower case?

1

There are 1 best solutions below

5
knittl On BEST ANSWER

For your given input, the following should work, no?

.[] | select(.field1 | ascii_downcase == "object1_value1") | .field1, .field3

To suppress errors for non-existing fields, append ?:

.[] | select(.field1 | ascii_downcase? == "object1_value1") | .field1, .field3

You can also try filtering on the presence of the field first:

.[] | select(has("field1")) | select(.field1 | ascii_downcase == "object1_value1") | .field1, .field3

Output:

Object1_Value1
Object1_Value3