sh/jshn.sh: add json_for_each_item()
authorHans Dedecker <dedeckeh@gmail.com>
Thu, 1 Feb 2018 15:41:27 +0000 (16:41 +0100)
committerHans Dedecker <dedeckeh@gmail.com>
Thu, 8 Feb 2018 11:15:20 +0000 (12:15 +0100)
Function usefull to iterate through the different elements of an
array or object; the provided callback function is called for each
element which is passed the value, key and user provided arguments.
For field types different from array or object the callback is called
with the retrieved value.

Signed-off-by: Hans Dedecker <dedeckeh@gmail.com>
Acked-by: Jo-Philipp Wich <jo@mein.io>
sh/jshn.sh

index 66baccbcaacff184ec25371fcdaf8159f1223dd0..7b0155d0ce4c0ec5a4cd8438a1ecf7441f2c4868 100644 (file)
@@ -288,3 +288,28 @@ json_is_a() {
        json_get_type type "$1"
        [ "$type" = "$2" ]
 }
+
+json_for_each_item() {
+       [ "$#" -ge 2 ] || return 0
+       local function="$1"; shift
+       local target="$1"; shift
+       local type val
+
+       json_get_type type "$target"
+       case "$type" in
+               object|array)
+                       local keys key
+                       json_select "$target"
+                       json_get_keys keys
+                       for key in $keys; do
+                               json_get_var val "$key"
+                               eval "$function \"\$val\" \"\$key\" \"\$@\""
+                       done
+                       json_select ..
+               ;;
+               *)
+                       json_get_var val "$target"
+                       eval "$function \"\$val\" \"\" \"\$@\""
+               ;;
+       esac
+}