]> git.corax.cc Git - toolbox/commitdiff
include/json: Fix error handling in json_array_head()
authorMatthias Kruk <m@m10k.eu>
Sat, 7 Jan 2023 07:54:55 +0000 (16:54 +0900)
committerMatthias Kruk <m@m10k.eu>
Sat, 7 Jan 2023 08:03:26 +0000 (17:03 +0900)
Because json_array_head() does not correctly check the return value
from jq, it does not correctly detect if an array is empty.

This commit fixes the function so that it does not rely on the return
value from `jq -e', since it returns an error if the boolean value false
was retrieved.

include/json.sh

index af81d18d1549175eee2cc92602dc1fd39a7e0c0d..862747ac11f3c3b6c8ee2dfd1e7a34ed2bfaedf8 100644 (file)
@@ -237,14 +237,21 @@ json_array_head() {
        local array="$1"
 
        local head
+       local string_re
 
-       head=$(jq -e -r '.[0]' <<< "$array")
+       string_re='^"(.*)"$'
 
-       if (( $? > 1 )); then
+       if ! head=$(jq '.[0]' <<< "$array") ||
+          [[ "$head" == "null" ]]; then
                return 1
        fi
 
-       echo "$head"
+       if [[ "$head" =~ $string_re ]]; then
+               echo "${BASH_REMATCH[1]}"
+       else
+               echo "$head"
+       fi
+
        return 0
 }