'How to return an entire json object when grep'ing jq output?
I have this json file - test.json
{"type":"RECORD","record":{"key_A": "apples","key_B":"bananas"}}
Then I do
cat test.json | jq '. | {first_fruit: .record.key_A,second_fruit:.record.key_B}' | grep "bananas"
"second_fruit": "bananas"
So it only shows me the "second_fruit":"bananas" line. Is there a way to return the object that contains that grep match? So it should return
{
"first_fruit": "apples",
"second_fruit": "bananas"
}
Solution 1:[1]
grep filters on the textual representation. Stay in jq to perform a logical filter, e.g. using select and any to forward only those inputs for which at least one (any) field value (.[]) matches (==) the given string.
jq '
{first_fruit: .record.key_A,second_fruit:.record.key_B}
| select(any(.[]; . == "bananas"))
'
{
"first_fruit": "apples",
"second_fruit": "bananas"
}
Or more efficiently, as @peak pointed out, you may want to select first and then shape the output:
.record | select(any(.[]; . == "bananas"))
| {first_fruit: .key_A, second_fruit: .key_B}
Instead of finding exact matches with ==, you can also use contains for partial matches, or test for a full regex test.
select(any(.[]; contains("bananas")))
select(any(.[]; test("bananas")))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
