Last active
March 22, 2025 00:02
-
-
Save pedroxs/f0ee8c515eea0dbce2e23eea7c048e10 to your computer and use it in GitHub Desktop.
jq - recursive search for keys containing "string" stripping empty results
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# recursive search for keys containing "string" stripping empty results | |
jq '.. | objects | with_entries(select(.key | contains("ftp"))) | select(. != {})' | |
# same, but output propper array | |
jq '[ .. | objects | with_entries(select(.key | contains("ftp"))) | select(. != {}) ]' | |
# or | |
jq 'map( .. | objects | with_entries(select(.key | contains("ftp"))) | select(. != {}) )' | |
# transform input from {type: a, amount: 1} to {a: 1} and sum all values by type | |
jq '[ .[] | {(.type): .amount} ] | map(to_entries) | add | group_by(.key) | map({key: .[0].key, value: map(.value) | add}) | from_entries' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great query! Here's some explainations(from copilot), in case there's someone like me doesn't know jq so well to understand it :)
The provided
jq
query is used to filter and transform JSON objects. Here's a step-by-step explanation of what each part of the query does:..
:| objects
:| with_entries(select(.key | contains("ftp")))
:with_entries
is a function that processes each key-value pair of an object.select(.key | contains("ftp"))
filters the key-value pairs to include only those where the key contains the string"ftp"
.| select(. != {})
:Putting it all together, the query recursively searches through the JSON structure, selects objects, and then filters those objects to include only key-value pairs where the key contains
"ftp"
. Finally, it removes any empty objects from the results.