Last active
June 11, 2019 16:56
-
-
Save eliranmal/9c330d6adbe9f92040fabb9d93816d45 to your computer and use it in GitHub Desktop.
a bash json parser via node js
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
#!/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