This repository was archived by the owner on Dec 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjisoni.v
142 lines (131 loc) · 2.18 KB
/
jisoni.v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
module jisoni
pub interface Serializable {
from_json(f Any)
to_json() string
}
// Decodes a JSON string into an `Any` type. Returns an option.
pub fn raw_decode(src string) ?Any {
mut p := new_parser(src)
p.detect_parse_mode()
if p.mode == .invalid {
return error('[jisoni] ' + p.emit_error('Invalid JSON.'))
}
fi := p.decode_value() or {
return error('[jisoni] ' + p.emit_error(err))
}
if p.tok.kind != .eof {
return error('[jisoni] ' + p.emit_error('Unknown token `$p.tok.kind`.'))
}
return fi
}
// A generic function that decodes a JSON string into the target type.
pub fn decode<T>(src string) T {
res := raw_decode(src) or {
panic(err)
}
mut typ := T{}
typ.from_json(res)
return typ
}
// A generic function that encodes a type into a JSON string.
pub fn encode<T>(typ T) string {
return typ.to_json()
}
// A simple function that returns `Null` struct. For use on constructing an `Any` object.
pub fn null() Null {
return Null{}
}
// Use `Any` as a map.
pub fn (f Any) as_map() map[string]Any {
mut mp := map[string]Any
match f {
map[string]Any {
return f
}
string {
mp['0'] = f
return mp
}
int {
mp['0'] = f
return mp
}
bool {
mp['0'] = f
return mp
}
f64 {
mp['0'] = f
return mp
}
Null {
mp['0'] = f
return mp
}
else {
if typeof(f) == 'array_Any' {
arr := f as []Any
for i, fi in arr {
mp[i.str()] = fi
}
return mp
}
return mp
}
}
}
// Use `Any` as a string.
pub fn (f Any) as_str() string {
match f {
string {
return f.str().trim_left('"').trim_right('"')
}
else {
return f.str()
}
}
}
// Use `Any` as an integer.
pub fn (f Any) as_int() int {
match f {
int {
return *f
}
f64 {
return f.str().int()
}
else {
return 0
}
}
}
// Use `Any` as a float.
pub fn (f Any) as_f() f64 {
match f {
int {
return f.str().f64()
}
f64 {
return *f
}
else {
return 0.0
}
}
}
// Use `Any` as an array.
pub fn (f Any) as_arr() []Any {
if typeof(f) == 'array_Any' {
arr := f as []Any
return *arr
}
if f is map[string]string {
mut arr := []Any{}
mp := *(f as map[string]Any)
for _, v in mp {
arr << v
}
return arr
}
return [f]
}