From: Matthias Kruk Date: Fri, 21 May 2021 06:39:19 +0000 (+0900) Subject: include/json: Allow arrays, objects as input to json_array() and json_object() X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=948a3a179904b7b15aed6b8c1b988d3e7fcdf01c;p=toolbox include/json: Allow arrays, objects as input to json_array() and json_object() The json_array() and json_object() functions currently can only be used to construct arrays and objects containing strings and integers. This commit modifies the functions so that they can also encode objects and arrays within objects and arrays. --- diff --git a/include/json.sh b/include/json.sh index 569c6e8..1d009a5 100644 --- a/include/json.sh +++ b/include/json.sh @@ -26,6 +26,14 @@ json_object() { local name local value + local re_number + local re_object + local re_array + + re_number='^[0-9]+$' + re_object='^{.*}$' + re_array='^\[.*\]$' + name="${!i}" ((i++)) value="${!i}" @@ -38,8 +46,13 @@ json_object() { printf ', ' fi - if [[ "$value" =~ ^[0-9]+$ ]]; then + if [[ "$value" =~ $re_number ]]; then printf '"%s": %d' "$name" "$value" + + elif [[ "$value" =~ $re_object ]] || + [[ "$value" =~ $re_array ]]; then + printf '"%s": %s' "$name" "$value" + else printf '"%s": "%s"' "$name" "$value" fi @@ -55,6 +68,14 @@ json_array() { local arg local n + local re_number + local re_object + local re_array + + re_number='^[0-9]+$' + re_object='^{.*}$' + re_array='^\[.*\]$' + printf "[" n=0 @@ -67,8 +88,13 @@ json_array() { printf ", " fi - if [[ "$arg" =~ ^[0-9]+$ ]]; then + if [[ "$arg" =~ $re_number ]]; then printf '%d' "$arg" + + elif [[ "$arg" =~ $re_object ]] || + [[ "$arg" =~ $re_array ]]; then + printf '%s' "$arg" + else printf '"%s"' "$arg" fi