From b3cf44567d9a01f8bdba85ddcf5df2f3d070d55d Mon Sep 17 00:00:00 2001 From: Matthias Kruk Date: Fri, 28 May 2021 21:12:16 +0900 Subject: [PATCH] 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 --- include/json.sh | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) 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 +} -- 2.47.3