]> git.corax.cc Git - toolbox/commitdiff
include/json: Add functions for creating json objects and arrays
authorMatthias Kruk <m@m10k.eu>
Wed, 24 Mar 2021 22:20:36 +0000 (07:20 +0900)
committerMatthias Kruk <m@m10k.eu>
Wed, 24 Mar 2021 22:20:36 +0000 (07:20 +0900)
Especially when interacting with REST-ful APIs via curl, it can be handy
to have functions to quickly generate JSON objects without having to
invoke jq. This commit adds functions for generating simple JSON objects
and arrays.

include/json.sh [new file with mode: 0644]

diff --git a/include/json.sh b/include/json.sh
new file mode 100644 (file)
index 0000000..569c6e8
--- /dev/null
@@ -0,0 +1,81 @@
+#!/bin/bash
+
+__init() {
+       if ! include "log"; then
+               return 1
+       fi
+
+       return 0
+}
+
+json_object() {
+        local argc
+        local i
+        local nvps
+
+        argc="$#"
+        nvps=0
+
+        if (( argc % 2 != 0 )); then
+                log_error "Invalid number of arguments"
+                return 1
+        fi
+
+        printf "{"
+        for (( i = 1; i <= argc; i++ )); do
+                local name
+                local value
+
+                name="${!i}"
+                ((i++))
+                value="${!i}"
+
+                if [ -z "$name" ] || [ -z "$value" ]; then
+                        continue
+                fi
+
+                if (( nvps > 0 )); then
+                        printf ', '
+                fi
+
+                if [[ "$value" =~ ^[0-9]+$ ]]; then
+                        printf '"%s": %d' "$name" "$value"
+                else
+                        printf '"%s": "%s"' "$name" "$value"
+                fi
+
+                ((nvps++))
+        done
+        printf "}\n"
+
+        return 0
+}
+
+json_array() {
+       local arg
+       local n
+
+       printf "["
+       n=0
+
+       for arg in "$@"; do
+               if [ -z "$arg" ]; then
+                       continue
+               fi
+
+               if (( n > 0 )); then
+                       printf ", "
+               fi
+
+               if [[ "$arg" =~ ^[0-9]+$ ]]; then
+                       printf '%d' "$arg"
+               else
+                       printf '"%s"' "$arg"
+               fi
+
+               ((n++))
+       done
+       printf "]\n"
+
+       return 0
+}