From: Matthias Kruk Date: Sat, 7 Jan 2023 07:54:55 +0000 (+0900) Subject: include/json: Fix error handling in json_array_head() X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=7209457792db2a23282dfd39c148e0ffcc4e2b40;p=toolbox include/json: Fix error handling in json_array_head() 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. --- diff --git a/include/json.sh b/include/json.sh index af81d18..862747a 100644 --- a/include/json.sh +++ b/include/json.sh @@ -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 }