Skip to content

Commit af62471

Browse files
committed
x.json2: add a convenience Any.as_map_of_strings/0 method
1 parent ec0b70e commit af62471

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

‎vlib/x/json2/json2.v‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,26 @@ pub fn (f Any) as_map() map[string]Any {
231231
}
232232
}
233233

234+
pub fn (f Any) as_map_of_strings() map[string]string {
235+
if f is map[string]Any {
236+
mut ms := map[string]string{}
237+
for k, v in f {
238+
ms[k] = v.str()
239+
}
240+
return ms
241+
}
242+
if f is []Any {
243+
mut ms := map[string]string{}
244+
for i, fi in f {
245+
ms['${i}'] = fi.str()
246+
}
247+
return ms
248+
}
249+
return {
250+
'0': f.str()
251+
}
252+
}
253+
234254
// to_time uses `Any` as a time.Time.
235255
pub fn (f Any) to_time() !time.Time {
236256
match f {

‎vlib/x/json2/tests/any_test.v‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,15 @@ fn test_as_map() {
8989
assert sample_data['obj'] or { 0 }.as_map()['foo'] or { 0 }.int() == 10
9090
}
9191

92+
fn test_as_map_of_strings() {
93+
assert sample_data['obj']!.as_map() == {
94+
'foo': json.Any(10)
95+
}
96+
assert sample_data['obj']!.as_map_of_strings() == {
97+
'foo': '10'
98+
}
99+
}
100+
92101
fn test_arr() {
93102
assert sample_data['int'] or { 0 }.arr()[0].int() == 1
94103
assert sample_data['i64'] or { 0 }.arr()[0].i64() == 128.0

0 commit comments

Comments
 (0)