From bbd6a465ab6c3dfc96e0c63f0a42808a9f88302d Mon Sep 17 00:00:00 2001 From: Matthias Kruk Date: Thu, 25 Mar 2021 07:20:36 +0900 Subject: [PATCH] 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. --- include/json.sh | 81 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 include/json.sh 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 +} -- 2.47.3