sh/jshn.sh: fix json_get_var() and json_get_type() to not return cached values
[project/libubox.git] / sh / jshn.sh
index 7389f8c..0f209d3 100644 (file)
@@ -19,11 +19,15 @@ json_add_generic() {
        local val="$3"
        local cur="${4:-$JSON_CUR}"
 
-       [ "${cur%%[0-9]*}" = "JSON_ARRAY" ] && {
+       if [ "${cur%%[0-9]*}" = "JSON_ARRAY" ]; then
                eval "local aseq=\"\${SEQ_$cur}\""
                var=$(( ${aseq:-0} + 1 ))
                export -- "SEQ_$cur=$var"
-       }
+       else
+               local name="${var//[^a-zA-Z0-9_]/_}"
+               [[ "$name" == "$var" ]] || export -- "NAME_${cur}_${name}=$var"
+               var="$name"
+       fi
 
        export -- "${cur}_$var=$val"
        export -- "TYPE_${cur}_$var=$type"
@@ -90,14 +94,21 @@ json_dump() {
 
 json_get_type() {
        local dest="$1"
-       local var="$2"
-       eval "export -- \"$dest=\${TYPE_${JSON_CUR}_$var}\""
+       local var="TYPE_${JSON_CUR}_$2"
+       eval "export -- \"$dest=\${$var}\"; [ -n \"\${$var+x}\" ]"
 }
 
 json_get_var() {
        local dest="$1"
-       local var="$2"
-       eval "export -- \"$dest=\${${JSON_CUR}_$var}\""
+       local var="${JSON_CUR}_${2//[^a-zA-Z0-9_]/_}"
+       eval "export -- \"$dest=\${$var}\"; [ -n \"\${$var+x}\" ]"
+}
+
+json_get_vars() {
+       while [ "$#" -gt 0 ]; do
+               local _var="$1"; shift
+               json_get_var "$_var" "$_var"
+       done
 }
 
 json_select() {
@@ -106,11 +117,11 @@ json_select() {
 
        [ -z "$1" ] && {
                JSON_CUR="JSON_VAR"
-               return
+               return 0
        }
        [[ "$1" == ".." ]] && {
                eval "JSON_CUR=\"\${UP_$JSON_CUR}\""
-               return;
+               return 0
        }
        json_get_type type "$target"
        case "$type" in
@@ -119,6 +130,7 @@ json_select() {
                ;;
                *)
                        echo "WARNING: Variable '$target' does not exist or is not an array/object"
+                       return 1
                ;;
        esac
 }