From: Matthias Kruk Date: Fri, 28 May 2021 12:12:16 +0000 (+0900) Subject: include/json: Add functions for manipulating JSON arrays X-Git-Url: https://git.corax.cc/?a=commitdiff_plain;h=b3cf44567d9a01f8bdba85ddcf5df2f3d070d55d;p=toolbox include/json: Add functions for manipulating JSON arrays Handling JSON arrays in shell scripts can be painful without jq. This commit adds a number of convenience functions that wrap jq to make array handling easier. The follow fuctions are added: - json_array_head(): Returns the first element of a JSON array - json_array_tail(): Returns a new JSON array without the first element - json_array_to_lines(): Returns all elements of a JSON array, one per line --- diff --git a/include/json.sh b/include/json.sh index 341a240..789f5a5 100644 --- a/include/json.sh +++ b/include/json.sh @@ -105,3 +105,47 @@ json_array() { return 0 } + +json_array_head() { + local array="$1" + + local head + + if ! head=$(jq -e -r '.[0]' <<< "$array"); then + return 1 + fi + + echo "$head" + return 0 +} + +json_array_tail() { + local array="$1" + + local tail + local element + local new + + tail=() + + while read -r element; do + tail+=("$element") + done < <(jq -r '.[1:][]' <<< "$array") + + if ! new=$(json_array "${tail[@]}"); then + return 1 + fi + + echo "$new" + return 0 +} + +json_array_to_lines() { + local array="$1" + + if ! jq -r '.[]' <<< "$array"; then + return 1 + fi + + return 0 +}