]> git.corax.cc Git - toolbox/commitdiff
include/json: Add functions for manipulating JSON arrays
authorMatthias Kruk <matthias.kruk@miraclelinux.com>
Fri, 28 May 2021 12:12:16 +0000 (21:12 +0900)
committerMatthias Kruk <matthias.kruk@miraclelinux.com>
Fri, 28 May 2021 12:12:16 +0000 (21:12 +0900)
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

index 341a240187efa8678cfa3d517ac7933773af6e48..789f5a5b1b8ae90a261c802f37a170019c191163 100644 (file)
@@ -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
+}