Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json2: add support for nested structs (fix #19549) #19579

Merged
merged 1 commit into from
Oct 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions vlib/x/json2/decode_struct_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ mut:
val T
}

struct StructTypeSub {
test string
}

struct StructTypeOption[T] {
mut:
val ?T
Expand Down Expand Up @@ -94,4 +98,11 @@ fn test_types() {
// dump(err)
assert true
}

assert json.decode[StructType[StructTypeSub]]('{"val": {"test": "test"}}')!.val.test == 'test'
if x := json.decode[StructType[StructTypeSub]]('{"val": {"invalid_field": "test"}}') {
assert false
} else {
assert true
}
}
9 changes: 7 additions & 2 deletions vlib/x/json2/json2.v
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,13 @@ 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()
return decode_struct[T](T{}, res)
}

// decode_struct is a generic function that decodes a JSON map into the struct T.
fn decode_struct[T](_ T, res map[string]Any) !T {
mut typ := T{}
$if T is $struct {
$for field in T.fields {
mut json_name := field.name
Expand Down Expand Up @@ -123,8 +128,8 @@ pub fn decode[T](src string) !T {
typ.$(field.name) = res[json_name]!.to_time()!
}
} $else $if field.is_array {
// typ.$(field.name) = res[field.name]!.arr()
} $else $if field.is_struct {
typ.$(field.name) = decode_struct(typ.$(field.name), res[field.name]!.as_map())!
} $else $if field.is_alias {
} $else $if field.is_map {
} $else {
Expand Down
Loading