diff --git a/vlib/x/json2/json2.v b/vlib/x/json2/json2.v index 9cf49d935b..8713234cee 100644 --- a/vlib/x/json2/json2.v +++ b/vlib/x/json2/json2.v @@ -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 { diff --git a/vlib/x/json2/tests/any_test.v b/vlib/x/json2/tests/any_test.v index 4ae9d35349..003b1d11d0 100644 --- a/vlib/x/json2/tests/any_test.v +++ b/vlib/x/json2/tests/any_test.v @@ -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