Skip to content

Instantly share code, notes, and snippets.

@eliranmal eliranmal/json.sh
Last active Jun 11, 2019

Embed
What would you like to do?
a bash json parser via node js
#!/usr/bin/env bash
# example usage:
#
# json_response="$(curl --flag http://whatever.man)" # -> { "status": 22, "errors": [ { "message": "oh no!" } ] }
# errors="$(echo "$json_response" | json_get "errors")"
# [[ $errors ]] && {
# msg="$(echo "$errors" | json_get "0" | json_get "message")"
# }
json_get() {
local prop_name="$1"
if hash node 2>/dev/null; then
printf "%s" "$(node -e '
var val=JSON.parse(process.argv[1] || "{}")["'"$prop_name"'"];
console.log(typeof val === "undefined" ? "" : typeof val === "string" ? val : JSON.stringify(val));
' "$(cat -)")"
else
printf "%s" "node is not installed! what are you doing?"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.