From: Matthias Kruk Date: Wed, 24 Mar 2021 22:20:36 +0000 (+0900) Subject: include/json: Add functions for creating json objects and arrays X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=bbd6a465ab6c3dfc96e0c63f0a42808a9f88302d;p=toolbox include/json: Add functions for creating json objects and arrays 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. --- diff --git a/include/json.sh b/include/json.sh new file mode 100644 index 0000000..569c6e8 --- /dev/null +++ b/include/json.sh @@ -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 +}