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:
parent
979066856b
commit
dc11f1fe05
@ -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
|
||||
}
|
||||
|
@ -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}}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user