2 # Adds command line aliases useful for dealing with JSON
4 # Check that user-defined method is installed
5 if [[ -n "$JSONTOOLS_METHOD" ]]; then
6 (( $+commands[$JSONTOOLS_METHOD] )) || unset JSONTOOLS_METHOD
9 # If method undefined, find the first one that is installed
10 if [[ -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
18 # If no methods were found, exit the plugin
19 [[ -n "$JSONTOOLS_METHOD" ]] || return 1
22 # Define json tools for each method
23 case "$JSONTOOLS_METHOD" in
25 # node doesn't make it easy to deal with stdin, so we pass it as an argument with xargs -0
27 xargs -0 node -e 'console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 4));'
32 json = JSON.parse(process.argv[1]);
41 function urlencode_json() {
42 xargs -0 node -e "console.log(encodeURIComponent(process.argv[1]))"
44 function urldecode_json() {
45 xargs -0 node -e "console.log(decodeURIComponent(process.argv[1]))"
50 python3 -c 'import sys; del sys.path[0]; import runpy; runpy._run_module_as_main("json.tool")'
54 import sys; del sys.path[0];
57 json.loads(sys.stdin.read())
58 print("true"); sys.exit(0)
60 print("false"); sys.exit(1)
63 function urlencode_json() {
65 import sys; del sys.path[0];
66 from urllib.parse import quote_plus
67 print(quote_plus(sys.stdin.read()))
70 function urldecode_json() {
72 import sys; del sys.path[0];
73 from urllib.parse import unquote_plus
74 print(unquote_plus(sys.stdin.read()))
83 puts JSON.parse(STDIN.read).to_yaml
90 puts !!JSON.parse(STDIN.read); exit(0)
91 rescue JSON::ParserError
96 function urlencode_json() {
97 ruby -e 'require "cgi"; puts CGI.escape(STDIN.read)'
99 function urldecode_json() {
100 ruby -e 'require "cgi"; puts CGI.unescape(STDIN.read)'
104 unset JSONTOOLS_METHOD
106 ## Add NDJSON support
108 function {pp,is,urlencode,urldecode}_ndjson() {
109 local json jsonfunc="${0//ndjson/json}"
110 while read -r json; do
111 $jsonfunc <<< "$json"