Skip to content

Instantly share code, notes, and snippets.

@snewell92
Last active May 25, 2023 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snewell92/b1ae5318d1ec6e888cf3de4595031edb to your computer and use it in GitHub Desktop.
Save snewell92/b1ae5318d1ec6e888cf3de4595031edb to your computer and use it in GitHub Desktop.
Conditionally pass to jq if the line looks a bit like jason
#!/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}"
@snewell92
Copy link
Author

I guess it would be more unixy if this was just is_json

cat messy-json.txt | is_json | jq -cC '.'

and I could alias that is_json | jq combo

@snewell92
Copy link
Author

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'

@snewell92
Copy link
Author

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