close
close
Jq Select Contains

Jq Select Contains

2 min read 24-01-2025
Jq Select Contains

jq is a powerful command-line JSON processor, and mastering its selectors is crucial for efficient data manipulation. One particularly useful selector is the contains operator, allowing you to filter JSON objects based on whether they contain specific strings or patterns. This post will guide you through effectively utilizing jq's contains functionality.

Understanding the contains Operator

The contains operator, denoted by | contains, checks if a string contains a specific substring. It returns true if the substring is found and false otherwise. Importantly, this is a case-sensitive operation.

Example:

Let's say you have a JSON file named data.json with the following content:

{
  "name": "John Doe",
  "city": "New York",
  "description": "A skilled developer working in New York City."
}

To check if the description field contains the substring "New York", you would use the following command:

jq '.description | contains("New York")' data.json

This will output:

true

If you changed the search term to something not present, like "London", the output would be false.

Beyond Simple String Matching

While simple string matching is useful, contains's power extends further. It integrates seamlessly with other jq features for more complex filtering:

Combining with select

The select function allows you to filter arrays based on a condition. Combined with contains, you can easily filter arrays of JSON objects:

Example:

Consider data2.json:

[
  {"name": "Alice", "skills": ["JavaScript", "Python"]},
  {"name": "Bob", "skills": ["Java", "C++"]},
  {"name": "Charlie", "skills": ["Python", "Go"]}
]

To select only the objects where the skills array contains "Python":

jq '.[] | select(.skills | contains("Python"))' data2.json

This efficiently filters the array, returning only Alice and Charlie's information.

Case-Insensitive Matching (Workaround)

As mentioned, contains is case-sensitive. For case-insensitive matching, you need to use a workaround involving lower:

jq '.description | lower | contains("new york")' data.json

This converts both the description and the search string to lowercase before the comparison, achieving case-insensitive matching.

Conclusion

The contains operator is a valuable tool in your jq arsenal. By understanding its functionality and combining it with other jq features, you can efficiently filter and manipulate JSON data, simplifying tasks involving string searching and array filtering within your JSON documents. Remember to consider case sensitivity and utilize workarounds like lower for case-insensitive searches when needed.

Related Posts


Latest Posts


Popular Posts