From: Matthias Kruk Date: Sat, 7 Jan 2023 08:33:53 +0000 (+0900) Subject: include/json: Fix parsing of output from jq in json_array_tail() X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=a0cb075b70ca2367c7f105c37217de3a844d0563;p=toolbox include/json: Fix parsing of output from jq in json_array_tail() The `json_array_tail()' function does not correctly handle return values and parse output from jq, causing it to incorrectly handle arrays that contain arrays or objects. This commit modifies `json_array_tail()' so that it correctly recognizes the type of data read from jq. --- diff --git a/include/json.sh b/include/json.sh index 862747a..832116c 100644 --- a/include/json.sh +++ b/include/json.sh @@ -261,12 +261,18 @@ json_array_tail() { local tail local element local new + local string_re + string_re='^"(.*)"$' tail=() while read -r element; do - tail+=("$element") - done < <(jq -r '.[1:][]' <<< "$array") + if [[ "$element" =~ $string_re ]]; then + tail+=("${BASH_REMATCH[1]}") + else + tail+=("$element") + fi + done < <(jq -c '.[1:][]' <<< "$array") if ! new=$(json_array "${tail[@]}"); then return 1 diff --git a/test/json_spec.sh b/test/json_spec.sh index bbe5e0d..0fe5f29 100644 --- a/test/json_spec.sh +++ b/test/json_spec.sh @@ -339,8 +339,8 @@ Describe "json_array_tail()" End It "removes an object from the head of the array" - When call json_array_tail '[{}, {"hello": "world"}]' - The stdout should equal '[{"hello": "world"}]' + When call json_array_tail '[{}, {"hello":"world"}]' + The stdout should equal '[{"hello":"world"}]' The status should equal 0 End End @@ -352,7 +352,7 @@ Describe "json_array_to_lines()" End It "splits a string array to lines" - When call json_array_to_lines '["hello", "world"]' + When call json_array_to_lines '["hello","world"]' The first line of stdout should equal "hello" The second line of stdout should equal "world" The status should equal 0