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

json2: encode array (#17926)

This commit is contained in:
Hitalo Souza
2023-04-10 13:54:43 -03:00
committed by GitHub
parent 319ad5bae2
commit 91874f3244
3 changed files with 19 additions and 14 deletions

View File

@ -200,6 +200,10 @@ fn test_option_array() {
val: false val: false
}] }]
assert json.encode(StructTypeOption[[]StructType[bool]]{ val: array_of_struct }) == '{"val":[{"val":true},{"val":false}]}' assert json.encode(StructTypeOption[[]StructType[bool]]{ val: array_of_struct }) == '{"val":[{"val":true},{"val":false}]}'
// assert json.encode(StructTypeOption[[][]int]{
// val: [[0, 1], [0, 2, 3], [2], [5, 1]]
// }) == '{"val":[[0,1],[0,2,3],[2],[5,1]]}'
} }
fn test_alias() { fn test_alias() {

View File

@ -127,9 +127,9 @@ fn test_encode_array() {
val: [true, false] val: [true, false]
}] }]
assert json.encode_array([1, 2, 3]) == '[1,2,3]' assert json.encode([1, 2, 3]) == '[1,2,3]'
assert json.encode_array(array_of_struct) == '[{"val":[false,true]},{"val":[true,false]}]' assert json.encode(array_of_struct) == '[{"val":[false,true]},{"val":[true,false]}]'
} }
fn test_encode_simple() { fn test_encode_simple() {

View File

@ -153,24 +153,25 @@ pub fn decode[T](src string) !T {
// encode is a generic function that encodes a type into a JSON string. // encode is a generic function that encodes a type into a JSON string.
pub fn encode[T](val T) string { pub fn encode[T](val T) string {
$if T is $array { $if T is $array {
$compile_error('Cannot use `json.encode` to encode array. Try `json.encode_array` instead') return encode_array(val)
} } $else {
mut sb := strings.new_builder(64) mut sb := strings.new_builder(64)
defer { defer {
unsafe { sb.free() } unsafe { sb.free() }
} }
default_encoder.encode_value(val, mut sb) or { default_encoder.encode_value(val, mut sb) or {
dump(err) dump(err)
default_encoder.encode_value[Null](null, mut sb) or {} default_encoder.encode_value[Null](null, mut sb) or {}
} }
return sb.str() return sb.str()
}
} }
// encode_array is a generic function that encodes a array into a JSON string. // encode_array is a generic function that encodes a array into a JSON string.
pub fn encode_array[T](val []T) string { fn encode_array[T](val []T) string {
mut sb := strings.new_builder(64) mut sb := strings.new_builder(64)
defer { defer {