Skip to content

Commit

Permalink
json2: fix decode to map doesn't work (#17757)
Browse files Browse the repository at this point in the history
  • Loading branch information
enghitalo committed Mar 24, 2023
1 parent 9790668 commit dc11f1f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
17 changes: 15 additions & 2 deletions vlib/x/json2/json2.v
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down
14 changes: 14 additions & 0 deletions vlib/x/json2/json2_test.v
Expand Up @@ -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}}
}

0 comments on commit dc11f1f

Please sign in to comment.