mirror of
https://github.com/vlang/v.git
synced 2025-09-13 22:42:26 +03:00
x.json2: add a convenience Any.as_map_of_strings/0 method
This commit is contained in:
parent
ec0b70e130
commit
af6247135c
2 changed files with 29 additions and 0 deletions
|
@ -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.
|
||||
pub fn (f Any) to_time() !time.Time {
|
||||
match f {
|
||||
|
|
|
@ -89,6 +89,15 @@ fn test_as_map() {
|
|||
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() {
|
||||
assert sample_data['int'] or { 0 }.arr()[0].int() == 1
|
||||
assert sample_data['i64'] or { 0 }.arr()[0].i64() == 128.0
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue