x.json2: add a convenience Any.as_map_of_strings/0 method

This commit is contained in:
Delyan Angelov 2025-03-08 16:49:29 +02:00
parent ec0b70e130
commit af6247135c
No known key found for this signature in database
GPG key ID: 66886C0F12D595ED
2 changed files with 29 additions and 0 deletions

View file

@ -231,6 +231,26 @@ pub fn (f Any) as_map() map[string]Any {
} }
} }
pub fn (f Any) as_map_of_strings() map[string]string {
if f is map[string]Any {
mut ms := map[string]string{}
for k, v in f {
ms[k] = v.str()
}
return ms
}
if f is []Any {
mut ms := map[string]string{}
for i, fi in f {
ms['${i}'] = fi.str()
}
return ms
}
return {
'0': f.str()
}
}
// to_time uses `Any` as a time.Time. // to_time uses `Any` as a time.Time.
pub fn (f Any) to_time() !time.Time { pub fn (f Any) to_time() !time.Time {
match f { match f {

View file

@ -89,6 +89,15 @@ fn test_as_map() {
assert sample_data['obj'] or { 0 }.as_map()['foo'] or { 0 }.int() == 10 assert sample_data['obj'] or { 0 }.as_map()['foo'] or { 0 }.int() == 10
} }
fn test_as_map_of_strings() {
assert sample_data['obj']!.as_map() == {
'foo': json.Any(10)
}
assert sample_data['obj']!.as_map_of_strings() == {
'foo': '10'
}
}
fn test_arr() { fn test_arr() {
assert sample_data['int'] or { 0 }.arr()[0].int() == 1 assert sample_data['int'] or { 0 }.arr()[0].int() == 1
assert sample_data['i64'] or { 0 }.arr()[0].i64() == 128.0 assert sample_data['i64'] or { 0 }.arr()[0].i64() == 128.0