Skip to content

Instantly share code, notes, and snippets.

@eliranmal
Last active June 11, 2019 16:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eliranmal/9c330d6adbe9f92040fabb9d93816d45 to your computer and use it in GitHub Desktop.
Save eliranmal/9c330d6adbe9f92040fabb9d93816d45 to your computer and use it in GitHub Desktop.
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