Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions sh/jshn.sh
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,20 @@ json_add_fields() {
done
}

json_get_index() {
local __dest="$1"
local __cur __parent __seq
_json_get_var __cur JSON_CUR
_json_get_var __parent "U_$__cur"
if [ "${__parent%%[0-9]*}" != "J_A" ]; then
[ -n "$_json_no_warning" ] || \
echo "WARNING: Not inside an array" >&2
return 1
fi
__seq="S_$__parent"
eval "export -- \"$__dest=\${$__seq}\"; [ -n \"\${$__seq+x}\" ]"
}

# functions read access to json variables

json_compact() {
Expand Down
37 changes: 37 additions & 0 deletions tests/shunit2/tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,43 @@ test_jshn_append_via_json_script() {
json_add_string "second" "value2"
json_get_keys keys
assertEquals "first second" "$keys"
set -u
}

test_jshn_get_index() {
JSON_PREFIX="${JSON_PREFIX:-}"
. ../../sh/jshn.sh

set +u

local index

json_init

json_add_object "DHCP4"

json_add_array "networks"

json_add_object ""
json_get_index index
json_add_int "id" 1
json_add_string "subnet" "192.168.1.0/24"
json_close_object

json_add_object ""
json_add_int "id" 2
json_add_string "subnet" "192.168.2.0/24"
json_close_object

json_select "$index" # revisit first anonymous object
json_add_int "valid-lifetime" 3600
json_select .. # pop back into array

json_close_array # networks

json_close_object # DHCP4

assertEquals '{ "DHCP4": { "networks": [ { "id": 1, "subnet": "192.168.1.0\/24", "valid-lifetime": 3600 }, { "id": 2, "subnet": "192.168.2.0\/24" } ] } }' "$(json_dump)"

set -u
}
Expand Down