]> git.corax.cc Git - toolbox/commitdiff
include/json: Allow arrays, objects as input to json_array() and json_object()
authorMatthias Kruk <matthias.kruk@miraclelinux.com>
Fri, 21 May 2021 06:39:19 +0000 (15:39 +0900)
committerMatthias Kruk <matthias.kruk@miraclelinux.com>
Fri, 21 May 2021 06:39:19 +0000 (15:39 +0900)
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.

include/json.sh

index 569c6e8b6088fead3dc95b15572be56fa37ddf0a..1d009a5d606ff7000e746544fa2808f57697d57d 100644 (file)
@@ -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