7ded6752fd34c513b0110b236c2ebd4fbbcd1a6f

Author
Eduardo Flores <eduardofv@gmail.com>
Committer
Marc Cornellà <hello@mcornella.com>
Date

Message

feat(jsontools): add tools to pretty print json-lines (ndjson) (#10176)

Co-authored-by: Marc Cornellà <hello@mcornella.com>

Diff

 1diff --git a/plugins/jsontools/README.md b/plugins/jsontools/README.md
 2index 1fa2b8eedb61296bdedec40319b73925688b29f2..6a2740014a9d2188fb11dba504fab36de50e38ab 100644
 3--- a/plugins/jsontools/README.md
 4+++ b/plugins/jsontools/README.md
 5@@ -17,32 +17,63 @@ Usage is simple... just take your json data and pipe it into the appropriate jso
 6 - `urlencode_json`: returns a url encoded string for the given json.
 7 - `urldecode_json`: returns decoded json for the given url encoded string.
 8 
 9+### Supports NDJSON (Newline Delimited JSON)
10+
11+The plugin also supports [NDJSON](http://ndjson.org/) input, which means all functions
12+have an alternative function that reads and processes the input line by line. These
13+functions have the same name except using `ndjson` instead of `json`:
14+
15+> `pp_ndjson`, `is_ndjson`, `urlencode_ndjson`, `urldecode_ndjson`.
16+
17 ### Examples
18 
19 - **pp_json**:
20 
21-```sh
22+```console
23 # curl json data and pretty print the results
24 curl https://coderwall.com/bobwilliams.json | pp_json
25 ```
26 
27 - **is_json**:
28 
29-```sh
30-# Validate if file's content conforms to a valid JSON schema
31-less data.json | is_json
32+```console
33+# validate if file's content conforms to a valid JSON schema
34+$ is_json < data.json
35+true
36+# shows true / false and returns the proper exit code
37+$ echo $?
38+0
39 ```
40 
41 - **urlencode_json**:
42 
43-```sh
44+```console
45 # json data directly from the command line
46-echo '{"b":2, "a":1}' | urlencode_json
47+$ echo '{"b":2, "a":1}' | urlencode_json
48+%7B%22b%22:2,%20%22a%22:1%7D
49 ```
50 
51 - **urldecode_json**:
52 
53-```sh
54+```console
55 # url encoded string to decode
56-echo '%7B%22b%22:2,%20%22a%22:1%7D%0A' | urldecode_json
57+$ echo '%7B%22b%22:2,%20%22a%22:1%7D' | urldecode_json
58+{"b":2, "a":1}
59+```
60+
61+- **pp_ndjson**:
62+
63+```console
64+# echo two separate json objects and pretty print both
65+$ echo '{"a": "b"}\n{"c": [1,2,3]}' | pp_ndjson
66+{
67+    "a": "b"
68+}
69+{
70+    "c": [
71+        1,
72+        2,
73+        3
74+    ]
75+}
76 ```
77diff --git a/plugins/jsontools/jsontools.plugin.zsh b/plugins/jsontools/jsontools.plugin.zsh
78index b518288ad65ac1ef168ba8f744d9b58809decf4e..ed45cfa8ebcd10389878c5a8355a44b6cf60b24f 100644
79--- a/plugins/jsontools/jsontools.plugin.zsh
80+++ b/plugins/jsontools/jsontools.plugin.zsh
81@@ -101,5 +101,13 @@ print(unquote_plus(sys.stdin.read()))
82     }
83   ;;
84 esac
85-
86 unset JSONTOOLS_METHOD
87+
88+## Add NDJSON support
89+
90+function {pp,is,urlencode,urldecode}_ndjson() {
91+  local json jsonfunc="${0//ndjson/json}"
92+  while read -r json; do
93+    $jsonfunc <<< "$json"
94+  done
95+}