jsontools.plugin.zsh 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # JSON Tools
  2. # Adds command line aliases useful for dealing with JSON
  3. if [[ $(whence $JSONTOOLS_METHOD) = "" ]]; then
  4. JSONTOOLS_METHOD=""
  5. fi
  6. if [[ $(whence node) != "" && ( "x$JSONTOOLS_METHOD" = "x" || "x$JSONTOOLS_METHOD" = "xnode" ) ]]; then
  7. alias pp_json='xargs -0 node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 4));"'
  8. 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); }"'
  9. alias urlencode_json='xargs -0 node -e "console.log(encodeURIComponent(process.argv[1]))"'
  10. alias urldecode_json='xargs -0 node -e "console.log(decodeURIComponent(process.argv[1]))"'
  11. elif [[ $(whence python) != "" && ( "x$JSONTOOLS_METHOD" = "x" || "x$JSONTOOLS_METHOD" = "xpython" ) ]]; then
  12. alias pp_json='python -c "import sys; del sys.path[0]; import runpy; runpy._run_module_as_main(\"json.tool\")"'
  13. alias is_json='python -c "
  14. import sys; del sys.path[0];
  15. import json;
  16. try:
  17. json.loads(sys.stdin.read())
  18. except ValueError, e:
  19. print False
  20. else:
  21. print True
  22. sys.exit(0)"'
  23. alias urlencode_json='python -c "
  24. import sys; del sys.path[0];
  25. import urllib, json;
  26. print urllib.quote_plus(sys.stdin.read())
  27. sys.exit(0)"'
  28. alias urldecode_json='python -c "
  29. import sys; del sys.path[0];
  30. import urllib, json;
  31. print urllib.unquote_plus(sys.stdin.read())
  32. sys.exit(0)"'
  33. elif [[ $(whence ruby) != "" && ( "x$JSONTOOLS_METHOD" = "x" || "x$JSONTOOLS_METHOD" = "xruby" ) ]]; then
  34. alias pp_json='ruby -e "require \"json\"; require \"yaml\"; puts JSON.parse(STDIN.read).to_yaml"'
  35. alias is_json='ruby -e "require \"json\"; begin; JSON.parse(STDIN.read); puts true; rescue Exception => e; puts false; end"'
  36. alias urlencode_json='ruby -e "require \"uri\"; puts URI.escape(STDIN.read)"'
  37. alias urldecode_json='ruby -e "require \"uri\"; puts URI.unescape(STDIN.read)"'
  38. fi
  39. unset JSONTOOLS_METHOD