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
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
+}