Last active
May 25, 2023 07:42
-
-
Save snewell92/b1ae5318d1ec6e888cf3de4595031edb to your computer and use it in GitHub Desktop.
Conditionally pass to jq if the line looks a bit like jason
This file contains 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
#!/bin/zsh | |
# Conditionally pass line or file data to jq. | |
# | |
# First argument is a filter override to jq, default is '.' | |
# Second argument is a file, otherwise stdin is used | |
JQ_FILTER=${1:-'.'} | |
while read line | |
do | |
FIRST=${line:0:1} | |
LAST=${line: -1} | |
if [[ "$FIRST" = "{" && "$LAST" = "}" ]]; then | |
echo "$line" | jq -cC $JQ_FILTER | |
fi | |
done < "${2:-/dev/stdin}" |
is_json.sh
would just be
#!/bin/zsh
# Filter by line if it looks like json
#
# First argument is a file, otherwise stdin is used
while read line
do
FIRST=${line:0:1}
LAST=${line: -1}
if [[ "$FIRST" = "{" && "$LAST" = "}" ]]; then
echo "$line"
fi
done < "${1:-/dev/stdin}"
And if you alias fjq="is_json | jq"
you can do cat messy-data.txt | fjq '.name'
Perhaps a grep regex could work better? Could essentially be a .trim()
as well
cat messy.txt | grep -E '^\b{.*}' | jq -Cc '.'
K that's my alias now, I like it.
# filtered to jq
alias fjq="grep -E '^\b{.*}' | jq"
#...
# Usage
cat messy.log | fjq -cC '.name'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess it would be more unixy if this was just
is_json
and I could alias that
is_json | jq
combo