Skip to content

Instantly share code, notes, and snippets.

@agzam
Last active December 13, 2024 02:50
Show Gist options
  • Save agzam/1b484c2fcb109d19e2964da7282442b7 to your computer and use it in GitHub Desktop.
Save agzam/1b484c2fcb109d19e2964da7282442b7 to your computer and use it in GitHub Desktop.
shell helper for exploring JSON in babashka REPL

Tiny helper function for exploring any JSON data in babashka REPL

Usage:

any_json_outputting_command | json2bb --repl

e.g.,

curl -s "https://api.thedogapi.com/v1/breeds" | json2bb --repl

once in the REPL, parsed EDN will be readily available in #'user/data, you can start exploring it:

(->> data count)

(->> data (map keys) set)

;; etc.

Also, you can instead use --nrepl-server option, connect to localhost:1667 from your editor and explore data that way.

If you simply want to convert JSON to EDN to print it out or pipe it further:

curl -s "https://api.thedogapi.com/v1/breeds" | json2bb --edn

Installation

Download it locally and:

Option 1: Source it in the shell config

echo 'source /path/to/json2bb.sh' >> ~/.zshrc

Option 2: Make it executable and link, or simply copy it somewhere in $PATH

chmod +x json2bb.sh
ln -s /path/to/json2bb.sh ~/bin/json2bb
#!/usr/bin/env bash
json2bb() {
if [ $# -eq 0 ] && [ -t 0 ]; then
cat <<EOF
json2bb - JSON to Clojure data processor
Usage: <json-input> | json2bb [option]
Options:
--edn Output pretty-printed EDN
--repl Start interactive Babashka REPL with data bound to 'data'
--nrepl-server Start nREPL server with data bound to 'data'
Examples:
curl api.example.com/data.json | json2bb
cat data.json | json2bb --repl
echo '{"a":1}' | json2bb --nrepl-server
EOF
return 0
fi
local mode=${1:---edn}
local tmpfile=$(mktemp)
cat > "$tmpfile"
case "$mode" in
--repl)
</dev/tty bb --init <(echo "(def data (json/parse-string (slurp \"$tmpfile\") true))") --repl
;;
--nrepl-server)
</dev/tty bb --init <(echo "(def data (json/parse-string (slurp \"$tmpfile\") true))") --nrepl-server
;;
--edn|"")
bb -e "(-> \"$tmpfile\" slurp (json/parse-string true) clojure.pprint/pprint)"
;;
esac
rm "$tmpfile"
}
if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
export -f json2bb
else
# Execute the function if script is run directly
json2bb "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment