diff --git a/vlib/x/json2/encode_struct_test.v b/vlib/x/json2/encode_struct_test.v index a1274285bd..68350c723f 100644 --- a/vlib/x/json2/encode_struct_test.v +++ b/vlib/x/json2/encode_struct_test.v @@ -200,6 +200,10 @@ fn test_option_array() { 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() { diff --git a/vlib/x/json2/encoder_test.v b/vlib/x/json2/encoder_test.v index 1033a5fc0d..f91a06212c 100644 --- a/vlib/x/json2/encoder_test.v +++ b/vlib/x/json2/encoder_test.v @@ -127,9 +127,9 @@ fn test_encode_array() { 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() { diff --git a/vlib/x/json2/json2.v b/vlib/x/json2/json2.v index 7d7714cfbd..ef7838dfa8 100644 --- a/vlib/x/json2/json2.v +++ b/vlib/x/json2/json2.v @@ -153,24 +153,25 @@ pub fn decode[T](src string) !T { // encode is a generic function that encodes a type into a JSON string. pub fn encode[T](val T) string { $if T is $array { - $compile_error('Cannot use `json.encode` to encode array. Try `json.encode_array` instead') - } - mut sb := strings.new_builder(64) + return encode_array(val) + } $else { + mut sb := strings.new_builder(64) - defer { - unsafe { sb.free() } - } + defer { + unsafe { sb.free() } + } - default_encoder.encode_value(val, mut sb) or { - dump(err) - default_encoder.encode_value[Null](null, mut sb) or {} - } + default_encoder.encode_value(val, mut sb) or { + dump(err) + 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. -pub fn encode_array[T](val []T) string { +fn encode_array[T](val []T) string { mut sb := strings.new_builder(64) defer {