1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

json2: fix decode to map doesn't work (#17757)

This commit is contained in:
Hitalo Souza 2023-03-24 12:30:32 -03:00 committed by GitHub
parent 979066856b
commit dc11f1fe05
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 2 deletions

View File

@ -21,8 +21,8 @@ pub fn fast_raw_decode(src string) !Any {
// decode is a generic function that decodes a JSON string into the target type.
pub fn decode[T](src string) !T {
mut typ := T{}
res := raw_decode(src)!.as_map()
$if T is $struct {
res := raw_decode(src)!.as_map()
$for field in T.fields {
mut json_name := field.name
for attr in field.attrs {
@ -132,7 +132,20 @@ pub fn decode[T](src string) !T {
}
}
} $else $if T is $map {
return error('Decode map is not allowed for now')
for k, v in res {
// // TODO - make this work to decode types like `map[string]StructType[bool]`
// $if typeof(typ[k]).idx is string {
// typ[k] = v.str()
// } $else $if typeof(typ[k]).idx is $struct {
// }
match v {
string {
typ[k] = v.str()
}
else {}
}
}
}
return typ
}

View File

@ -121,3 +121,17 @@ fn test_struct_with_struct_to_map() {
assert json.map_from(StructType[StructType[string]]{StructType[string]{'3'}}).str() == '{"val":{"val":"3"}}'
assert json.map_from(StructType[StructType[int]]{StructType[int]{3}}).str() == '{"val":{"val":3}}'
}
fn test_maps() {
assert json.decode[map[string]string]('{"test":"abc"}') or {
dump(err)
assert false
} == {
'test': 'abc'
}
// assert json.decode[map[string]StructType[bool]]('{"test":{"val":true}}') or {
// dump(err)
// assert false
// } == {"test":StructType[bool]{true}}
}