2020-09-10 12:05:40 +02:00
|
|
|
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
|
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
module json2
|
|
|
|
|
|
|
|
import strings
|
2020-10-09 16:11:55 +02:00
|
|
|
|
|
|
|
fn write_value(v Any, i int, len int, mut wr strings.Builder) {
|
|
|
|
str := v.str()
|
2020-11-25 12:09:40 +01:00
|
|
|
if v is string {
|
|
|
|
wr.write('"$str"')
|
|
|
|
} else {
|
2020-11-15 13:58:17 +01:00
|
|
|
wr.write(str)
|
|
|
|
}
|
2020-10-09 16:11:55 +02:00
|
|
|
if i >= len-1 { return }
|
|
|
|
wr.write_b(`,`)
|
|
|
|
}
|
|
|
|
|
2020-09-10 12:05:40 +02:00
|
|
|
// String representation of the `map[string]Any`.
|
|
|
|
pub fn (flds map[string]Any) str() string {
|
|
|
|
mut wr := strings.new_builder(200)
|
2020-10-09 16:11:55 +02:00
|
|
|
wr.write_b(`{`)
|
2020-09-10 12:05:40 +02:00
|
|
|
mut i := 0
|
|
|
|
for k, v in flds {
|
|
|
|
wr.write('"$k":')
|
2020-10-09 16:11:55 +02:00
|
|
|
write_value(v, i, flds.len, mut wr)
|
2020-09-10 12:05:40 +02:00
|
|
|
i++
|
|
|
|
}
|
2020-10-09 16:11:55 +02:00
|
|
|
wr.write_b(`}`)
|
|
|
|
defer {
|
|
|
|
wr.free()
|
|
|
|
}
|
|
|
|
res := wr.str()
|
|
|
|
return res
|
2020-09-10 12:05:40 +02:00
|
|
|
}
|
2020-10-09 16:11:55 +02:00
|
|
|
|
2020-09-10 12:05:40 +02:00
|
|
|
// String representation of the `[]Any`.
|
|
|
|
pub fn (flds []Any) str() string {
|
|
|
|
mut wr := strings.new_builder(200)
|
2020-10-09 16:11:55 +02:00
|
|
|
wr.write_b(`[`)
|
2020-09-10 12:05:40 +02:00
|
|
|
for i, v in flds {
|
2020-10-09 16:11:55 +02:00
|
|
|
write_value(v, i, flds.len, mut wr)
|
2020-09-10 12:05:40 +02:00
|
|
|
}
|
2020-10-09 16:11:55 +02:00
|
|
|
wr.write_b(`]`)
|
|
|
|
defer {
|
|
|
|
wr.free()
|
|
|
|
}
|
|
|
|
res := wr.str()
|
|
|
|
return res
|
2020-09-10 12:05:40 +02:00
|
|
|
}
|
2020-10-09 16:11:55 +02:00
|
|
|
|
2020-09-10 12:05:40 +02:00
|
|
|
// String representation of the `Any` type.
|
|
|
|
pub fn (f Any) str() string {
|
2020-11-25 12:09:40 +01:00
|
|
|
match f {
|
2020-11-24 13:58:29 +01:00
|
|
|
string { return f }
|
|
|
|
int { return f.str() }
|
|
|
|
i64 { return f.str() }
|
|
|
|
f32 { return f.str() }
|
|
|
|
f64 { return f.str() }
|
|
|
|
any_int { return f.str() }
|
|
|
|
any_float { return f.str() }
|
|
|
|
bool { return f.str() }
|
|
|
|
map[string]Any { return f.str() }
|
2020-09-10 12:05:40 +02:00
|
|
|
Null { return 'null' }
|
|
|
|
else {
|
|
|
|
if f is []Any {
|
2020-11-24 13:58:29 +01:00
|
|
|
return f.str()
|
2020-09-10 12:05:40 +02:00
|
|
|
}
|
|
|
|
return ''
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|