add jshn
[project/libubox.git] / sh / jshn.sh
1 # functions for parsing and generating json
2
3 append() {
4 local var="$1"
5 local value="$2"
6 local sep="${3:- }"
7
8 eval "export ${NO_EXPORT:+-n} -- \"$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=
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 export ${NO_EXPORT:+-n} -- "${cur}_$var=$val"
23 export ${NO_EXPORT:+-n} -- "TYPE_${cur}_$var=$type"
24 append JSON_UNSET "${cur}_$var TYPE_${cur}_$var"
25 append "KEYS_${cur}" "$var"
26 }
27
28 json_add_table() {
29 JSON_SEQ=$(($JSON_SEQ + 1))
30 append JSON_STACK "$JSON_CUR"
31 local table="JSON_TABLE$JSON_SEQ"
32 export ${NO_EXPORT:+-n} -- "UP_$table=$JSON_CUR"
33 JSON_CUR="$table"
34 }
35
36 json_add_object() {
37 local cur="$JSON_CUR"
38 json_add_table
39 json_add_generic object "$1" "$JSON_CUR" "$cur"
40 }
41
42 json_close_object() {
43 local oldstack="$JSON_STACK"
44 export "KEYS_${JSON_CUR}"
45 JSON_CUR="${JSON_STACK##* }"
46 JSON_STACK="${JSON_STACK% *}"
47 [[ "$oldstack" == "$JSON_STACK" ]] && JSON_STACK=
48 }
49
50 json_add_array() {
51 local cur="$JSON_CUR"
52 json_add_table
53 json_add_generic array "$1" "$JSON_CUR" "$cur"
54 }
55
56 json_close_array() {
57 json_close_object
58 }
59
60 json_add_string() {
61 json_add_generic string "$1" "$2"
62 }
63
64 json_add_int() {
65 json_add_generic int "$1" "$2"
66 }
67
68 json_add_boolean() {
69 json_add_generic boolean "$1" "$2"
70 }
71
72 # functions read access to json variables
73
74 json_load() {
75 eval `jshn -r "$1"`
76 }
77
78 json_dump() {
79 jshn -w
80 }
81
82 json_get_type() {
83 local dest="$1"
84 local var="$2"
85 eval "export ${NO_EXPORT:+-n} -- \"$dest=\${TYPE_${JSON_CUR}_$var}\""
86 }
87
88 json_get_var() {
89 local dest="$1"
90 local var="$2"
91 eval "export ${NO_EXPORT:+-n} -- \"$dest=\${${JSON_CUR}_$var}\""
92 }
93
94 json_select() {
95 local target="$1"
96 local type
97
98 [ -z "$1" ] && {
99 JSON_CUR="JSON_VAR"
100 return
101 }
102 [[ "$1" == ".." ]] && {
103 eval "JSON_CUR=\"\${UP_$JSON_CUR}\""
104 return;
105 }
106 json_get_type type "$target"
107 case "$type" in
108 object|array)
109 json_get_var JSON_CUR "$target"
110 ;;
111 *)
112 echo "WARNING: Variable '$target' does not exist or is not an array/object"
113 ;;
114 esac
115 }