Skip to content

Commit

Permalink
x.json2: add a way to decode an array (#21186)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Apr 6, 2024
1 parent 3d5dbca commit 9d88984
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions vlib/x/json2/decoder.v
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,25 @@ pub fn decode[T](src string) !T {
return decode_struct[T](T{}, res)
}

// decode_array is a generic function that decodes a JSON string into the array target type.
pub fn decode_array[T](src string) ![]T {
res := raw_decode(src)!.as_map()
return decode_struct_array(T{}, res)
}

// decode_struct_array is a generic function that decodes a JSON map into array struct T.
fn decode_struct_array[T](_ T, res map[string]Any) ![]T {
$if T is $struct {
mut arr := []T{}
for v in res.values() {
arr << decode_struct[T](T{}, v.as_map())!
}
return arr
} $else {
return error("The type `${T.name}` can't be decoded.")
}
}

// 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{}
Expand Down

0 comments on commit 9d88984

Please sign in to comment.