jsontools.plugin.zsh 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # JSON Tools
  2. # Adds command line aliases useful for dealing with JSON
  3. # Check that user-defined method is installed
  4. if [[ -n "$JSONTOOLS_METHOD" ]]; then
  5. (( $+commands[$JSONTOOLS_METHOD] )) || unset JSONTOOLS_METHOD
  6. fi
  7. # If method undefined, find the first one that is installed
  8. if [[ ! -v JSONTOOLS_METHOD ]]; then
  9. for JSONTOOLS_METHOD in node python ruby; do
  10. # If method found, break out of loop
  11. (( $+commands[$JSONTOOLS_METHOD] )) && break
  12. # Otherwise unset the variable
  13. unset JSONTOOLS_METHOD
  14. done
  15. # If no methods were found, exit the plugin
  16. [[ -v JSONTOOLS_METHOD ]] || return 1
  17. fi
  18. # Define json tools for each method
  19. case "$JSONTOOLS_METHOD" in
  20. node)
  21. alias pp_json='xargs -0 node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 4));"'
  22. alias is_json='xargs -0 node -e "try {json = JSON.parse(process.argv[1]);} catch (e) { console.log(false); json = null; } if(json) { console.log(true); }"'
  23. alias urlencode_json='xargs -0 node -e "console.log(encodeURIComponent(process.argv[1]))"'
  24. alias urldecode_json='xargs -0 node -e "console.log(decodeURIComponent(process.argv[1]))"'
  25. ;;
  26. python)
  27. alias pp_json='python -c "import sys; del sys.path[0]; import runpy; runpy._run_module_as_main(\"json.tool\")"'
  28. alias is_json='python -c "
  29. import sys; del sys.path[0];
  30. import json;
  31. try:
  32. json.loads(sys.stdin.read())
  33. except ValueError, e:
  34. print False
  35. else:
  36. print True
  37. sys.exit(0)"'
  38. alias urlencode_json='python -c "
  39. import sys; del sys.path[0];
  40. import urllib, json;
  41. print urllib.quote_plus(sys.stdin.read())
  42. sys.exit(0)"'
  43. alias urldecode_json='python -c "
  44. import sys; del sys.path[0];
  45. import urllib, json;
  46. print urllib.unquote_plus(sys.stdin.read())
  47. sys.exit(0)"'
  48. ;;
  49. ruby)
  50. alias pp_json='ruby -e "require \"json\"; require \"yaml\"; puts JSON.parse(STDIN.read).to_yaml"'
  51. alias is_json='ruby -e "require \"json\"; begin; JSON.parse(STDIN.read); puts true; rescue Exception => e; puts false; end"'
  52. alias urlencode_json='ruby -e "require \"uri\"; puts URI.escape(STDIN.read)"'
  53. alias urldecode_json='ruby -e "require \"uri\"; puts URI.unescape(STDIN.read)"'
  54. ;;
  55. esac
  56. unset JSONTOOLS_METHOD