jshn: clear more variables on json_init, fix adding array elements
[project/libubox.git] / sh / jshn.sh
1 # functions for parsing and generating json
2
3 jshn_append() {
4 local var="$1"
5 local value="$2"
6 local sep="${3:- }"
7
8 eval "export -- \"$var=\${$var:+\${$var}\${value:+\$sep}}\$value\""
9 }
10
11 json_init() {
12 [ -n "$JSON_UNSET" ] && eval "unset $JSON_UNSET"
13 export -- JSON_SEQ=0 JSON_STACK= JSON_CUR="JSON_VAR" JSON_UNSET="" KEYS_JSON_VAR= TYPE_JSON_VAR=
14 }
15
16 json_add_generic() {
17 local type="$1"
18 local var="$2"
19 local val="$3"
20 local cur="${4:-$JSON_CUR}"
21
22 [ "${cur%%[0-9]*}" = "JSON_ARRAY" ] && {
23 eval "local aseq=\"\${SEQ_$cur}\""
24 var=$(( ${aseq:-0} + 1 ))
25 export -- "SEQ_$cur=$var"
26 }
27
28 export -- "${cur}_$var=$val"
29 export -- "TYPE_${cur}_$var=$type"
30 jshn_append JSON_UNSET "${cur}_$var TYPE_${cur}_$var"
31 jshn_append "KEYS_${cur}" "$var"
32 }
33
34 json_add_table() {
35 local TYPE="$1"
36 JSON_SEQ=$(($JSON_SEQ + 1))
37 jshn_append JSON_STACK "$JSON_CUR"
38 local table="JSON_$TYPE$JSON_SEQ"
39 export -- "UP_$table=$JSON_CUR"
40 export -- "KEYS_$table="
41 jshn_append JSON_UNSET "KEYS_$table UP_$table"
42 [ "$TYPE" = "ARRAY" ] && jshn_append JSON_UNSET "SEQ_$table"
43 JSON_CUR="$table"
44 }
45
46 json_add_object() {
47 local cur="$JSON_CUR"
48 json_add_table TABLE
49 json_add_generic object "$1" "$JSON_CUR" "$cur"
50 }
51
52 json_close_object() {
53 local oldstack="$JSON_STACK"
54 JSON_CUR="${JSON_STACK##* }"
55 JSON_STACK="${JSON_STACK% *}"
56 [[ "$oldstack" == "$JSON_STACK" ]] && JSON_STACK=
57 }
58
59 json_add_array() {
60 local cur="$JSON_CUR"
61 json_add_table ARRAY
62 json_add_generic array "$1" "$JSON_CUR" "$cur"
63 }
64
65 json_close_array() {
66 json_close_object
67 }
68
69 json_add_string() {
70 json_add_generic string "$1" "$2"
71 }
72
73 json_add_int() {
74 json_add_generic int "$1" "$2"
75 }
76
77 json_add_boolean() {
78 json_add_generic boolean "$1" "$2"
79 }
80
81 # functions read access to json variables
82
83 json_load() {
84 eval `jshn -r "$1"`
85 }
86
87 json_dump() {
88 jshn "$@" -w
89 }
90
91 json_get_type() {
92 local dest="$1"
93 local var="$2"
94 eval "export -- \"$dest=\${TYPE_${JSON_CUR}_$var}\""
95 }
96
97 json_get_var() {
98 local dest="$1"
99 local var="$2"
100 eval "export -- \"$dest=\${${JSON_CUR}_$var}\""
101 }
102
103 json_select() {
104 local target="$1"
105 local type
106
107 [ -z "$1" ] && {
108 JSON_CUR="JSON_VAR"
109 return
110 }
111 [[ "$1" == ".." ]] && {
112 eval "JSON_CUR=\"\${UP_$JSON_CUR}\""
113 return;
114 }
115 json_get_type type "$target"
116 case "$type" in
117 object|array)
118 json_get_var JSON_CUR "$target"
119 ;;
120 *)
121 echo "WARNING: Variable '$target' does not exist or is not an array/object"
122 ;;
123 esac
124 }