diff mbox series

[1/2] jshn.sh: Add pretty-printing to json_dump

Message ID 20230414183705.1531142-1-philipp@redfish-solutions.com
State Accepted
Delegated to: Alexander Couzens
Headers show
Series [1/2] jshn.sh: Add pretty-printing to json_dump | expand

Commit Message

Philip Prindeville April 14, 2023, 6:37 p.m. UTC
From: Philip Prindeville <philipp@redfish-solutions.com>

If a JSON file might be read by a human, say for debugging, it
could be useful to pretty-print it.  We do this in places by
calling "json_dump -i" but it shouldn't be necessary to know the
arguments to "jshn" (and indeed, that's not portable if we retool
the underlying implementation). Conversely output that's ephemeral
doesn't need to be pretty (say being piped as input to another
command).

Signed-off-by: Philip Prindeville <philipp@redfish-solutions.com>
---
 sh/jshn.sh | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
diff mbox series

Patch

diff --git a/sh/jshn.sh b/sh/jshn.sh
index c97369230a93d144fbba06b5a8fa79c9acc41238..1d3055711820e5a21ea59cae49e7bf3f56b626d8 100644
--- a/sh/jshn.sh
+++ b/sh/jshn.sh
@@ -199,6 +199,16 @@  json_add_fields() {
 
 # functions read access to json variables
 
+json_compact() {
+	JSON_NONEWLINE=1
+	JSON_INDENT=
+}
+
+json_pretty() {
+	JSON_NONEWLINE=
+	JSON_INDENT=1
+}
+
 json_load() {
 	eval "`jshn -r "$1"`"
 }
@@ -208,7 +218,7 @@  json_load_file() {
 }
 
 json_dump() {
-	jshn "$@" ${JSON_PREFIX:+-p "$JSON_PREFIX"} -w 
+	jshn "$@" ${JSON_PREFIX:+-p "$JSON_PREFIX"} ${JSON_NONEWLINE:+-n} ${JSON_INDENT:+-i} -w
 }
 
 json_get_type() {