jsontools.plugin.zsh
2883 bytes
1# JSON Tools
2# Adds command line aliases useful for dealing with JSON
3
4# Check that user-defined method is installed
5if [[ -n "$JSONTOOLS_METHOD" ]]; then
6 (( $+commands[$JSONTOOLS_METHOD] )) || unset JSONTOOLS_METHOD
7fi
8
9# If method undefined, find the first one that is installed
10if [[ -z "$JSONTOOLS_METHOD" ]]; then
11 for JSONTOOLS_METHOD in node python3 ruby; do
12 # If method found, break out of loop
13 (( $+commands[$JSONTOOLS_METHOD] )) && break
14 # Otherwise unset the variable
15 unset JSONTOOLS_METHOD
16 done
17
18 # If no methods were found, exit the plugin
19 [[ -n "$JSONTOOLS_METHOD" ]] || return 1
20fi
21
22# Define json tools for each method
23case "$JSONTOOLS_METHOD" in
24 node)
25 # node doesn't make it easy to deal with stdin, so we pass it as an argument with xargs -0
26 function pp_json() {
27 xargs -0 node -e 'console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 4));'
28 }
29 function is_json() {
30 xargs -0 node -e '
31 try {
32 json = JSON.parse(process.argv[1]);
33 console.log("true");
34 process.exit(0);
35 } catch (e) {
36 console.log("false");
37 process.exit(1);
38 }
39 '
40 }
41 function urlencode_json() {
42 xargs -0 node -e "console.log(encodeURIComponent(process.argv[1]))"
43 }
44 function urldecode_json() {
45 xargs -0 node -e "console.log(decodeURIComponent(process.argv[1]))"
46 }
47 ;;
48 python3)
49 function pp_json() {
50 python3 -c 'import sys; del sys.path[0]; import runpy; runpy._run_module_as_main("json.tool")'
51 }
52 function is_json() {
53 python3 -c '
54import sys; del sys.path[0];
55import json
56try:
57 json.loads(sys.stdin.read())
58 print("true"); sys.exit(0)
59except ValueError:
60 print("false"); sys.exit(1)
61 '
62 }
63 function urlencode_json() {
64 python3 -c '
65import sys; del sys.path[0];
66from urllib.parse import quote_plus
67print(quote_plus(sys.stdin.read()))
68 '
69 }
70 function urldecode_json() {
71 python3 -c '
72import sys; del sys.path[0];
73from urllib.parse import unquote_plus
74print(unquote_plus(sys.stdin.read()))
75 '
76 }
77 ;;
78 ruby)
79 function pp_json() {
80 ruby -e '
81 require "json"
82 require "yaml"
83 puts JSON.parse(STDIN.read).to_yaml
84 '
85 }
86 function is_json() {
87 ruby -e '
88 require "json"
89 begin
90 puts !!JSON.parse(STDIN.read); exit(0)
91 rescue JSON::ParserError
92 puts false; exit(1)
93 end
94 '
95 }
96 function urlencode_json() {
97 ruby -e 'require "cgi"; puts CGI.escape(STDIN.read)'
98 }
99 function urldecode_json() {
100 ruby -e 'require "cgi"; puts CGI.unescape(STDIN.read)'
101 }
102 ;;
103esac
104unset JSONTOOLS_METHOD
105
106## Add NDJSON support
107
108function {pp,is,urlencode,urldecode}_ndjson() {
109 local json jsonfunc="${0//ndjson/json}"
110 while read -r json; do
111 $jsonfunc <<< "$json"
112 done
113}