same for json_get_var
[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 if [ "${cur%%[0-9]*}" = "JSON_ARRAY" ]; then
23 eval "local aseq=\"\${SEQ_$cur}\""
24 var=$(( ${aseq:-0} + 1 ))
25 export -- "SEQ_$cur=$var"
26 else
27 local name="$(echo -n "$var" | tr -C '[a-zA-Z_]' _)"
28 [[ "$name" == "$var" ]] || export -- "NAME_${cur}_${name}=$var"
29 var="$name"
30 fi
31
32 export -- "${cur}_$var=$val"
33 export -- "TYPE_${cur}_$var=$type"
34 jshn_append JSON_UNSET "${cur}_$var TYPE_${cur}_$var"
35 jshn_append "KEYS_${cur}" "$var"
36 }
37
38 json_add_table() {
39 local TYPE="$1"
40 JSON_SEQ=$(($JSON_SEQ + 1))
41 jshn_append JSON_STACK "$JSON_CUR"
42 local table="JSON_$TYPE$JSON_SEQ"
43 export -- "UP_$table=$JSON_CUR"
44 export -- "KEYS_$table="
45 jshn_append JSON_UNSET "KEYS_$table UP_$table"
46 [ "$TYPE" = "ARRAY" ] && jshn_append JSON_UNSET "SEQ_$table"
47 JSON_CUR="$table"
48 }
49
50 json_add_object() {
51 local cur="$JSON_CUR"
52 json_add_table TABLE
53 json_add_generic object "$1" "$JSON_CUR" "$cur"
54 }
55
56 json_close_object() {
57 local oldstack="$JSON_STACK"
58 JSON_CUR="${JSON_STACK##* }"
59 JSON_STACK="${JSON_STACK% *}"
60 [[ "$oldstack" == "$JSON_STACK" ]] && JSON_STACK=
61 }
62
63 json_add_array() {
64 local cur="$JSON_CUR"
65 json_add_table ARRAY
66 json_add_generic array "$1" "$JSON_CUR" "$cur"
67 }
68
69 json_close_array() {
70 json_close_object
71 }
72
73 json_add_string() {
74 json_add_generic string "$1" "$2"
75 }
76
77 json_add_int() {
78 json_add_generic int "$1" "$2"
79 }
80
81 json_add_boolean() {
82 json_add_generic boolean "$1" "$2"
83 }
84
85 # functions read access to json variables
86
87 json_load() {
88 eval `jshn -r "$1"`
89 }
90
91 json_dump() {
92 jshn "$@" -w
93 }
94
95 json_get_type() {
96 local dest="$1"
97 local var="$2"
98 eval "export -- \"$dest=\${TYPE_${JSON_CUR}_$var}\""
99 }
100
101 json_get_var() {
102 local dest="$1"
103 local var="$(echo -n "$2" | tr -C '[a-zA-Z_]' _)"
104 eval "export -- \"$dest=\${${JSON_CUR}_$var}\""
105 }
106
107 json_select() {
108 local target="$1"
109 local type
110
111 [ -z "$1" ] && {
112 JSON_CUR="JSON_VAR"
113 return
114 }
115 [[ "$1" == ".." ]] && {
116 eval "JSON_CUR=\"\${UP_$JSON_CUR}\""
117 return;
118 }
119 json_get_type type "$target"
120 case "$type" in
121 object|array)
122 json_get_var JSON_CUR "$target"
123 ;;
124 *)
125 echo "WARNING: Variable '$target' does not exist or is not an array/object"
126 ;;
127 esac
128 }