diff --git a/vlib/x/json2/encoder.v b/vlib/x/json2/encoder.v index bb935b84ca..2919b711eb 100644 --- a/vlib/x/json2/encoder.v +++ b/vlib/x/json2/encoder.v @@ -325,7 +325,7 @@ pub fn (f Any) prettify_json_str() string { } mut enc := Encoder{ newline: `\n` - newline_spaces_count: 4 + newline_spaces_count: 2 } enc.encode_value(f, mut sb) or {} return sb.str() diff --git a/vlib/x/json2/json2.v b/vlib/x/json2/json2.v index 7989c2f5ec..1ac3074637 100644 --- a/vlib/x/json2/json2.v +++ b/vlib/x/json2/json2.v @@ -82,6 +82,13 @@ pub fn encode[T](val T) string { return sb.str() } +// encode_pretty ... +pub fn encode_pretty[T](typed_data T) string { + encoded := encode(typed_data) + raw_decoded := raw_decode(encoded) or { 0 } + return raw_decoded.prettify_json_str() +} + // int uses `Any` as an integer. pub fn (f Any) int() int { match f { diff --git a/vlib/x/json2/json_module_compatibility_test/json_test.v b/vlib/x/json2/json_module_compatibility_test/json_test.v index 427c808861..9c700892bf 100644 --- a/vlib/x/json2/json_module_compatibility_test/json_test.v +++ b/vlib/x/json2/json_module_compatibility_test/json_test.v @@ -178,3 +178,37 @@ fn test_generic_struct() { assert foo_dec.name == 'bar' assert foo_dec.data == 12 } + +type StringAlias = string + +// TODO - encode_pretty array, sum types, struct, alias of struct and others... +struct Foo2 { + ux8 u8 + ux16 u16 + ux32 u32 + ux64 u64 + sx8 i8 + sx16 i16 + sx32 int + sx64 i64 + a bool + b string + c StringAlias +} + +fn test_pretty() { + foo := Foo2{1, 2, 3, 4, -1, -2, -3, -4, true, 'abc', 'aliens'} + assert json.encode_pretty(foo) == '{ + "ux8": 1, + "ux16": 2, + "ux32": 3, + "ux64": 4, + "sx8": -1, + "sx16": -2, + "sx32": -3, + "sx64": -4, + "a": true, + "b": "abc", + "c": "aliens" +}' +} diff --git a/vlib/x/json2/json_module_compatibility_test/json_todo_test.vv b/vlib/x/json2/json_module_compatibility_test/json_todo_test.vv index d986e67a69..0c238cc1ec 100644 --- a/vlib/x/json2/json_module_compatibility_test/json_todo_test.vv +++ b/vlib/x/json2/json_module_compatibility_test/json_todo_test.vv @@ -348,17 +348,6 @@ fn test_decode_missing_maps_field() { assert '${info.maps}' == '{}' } -struct Foo2 { - name string -} - -//! BUGFIX - .from_json(res) -fn test_pretty() { - foo := Foo2{'Bob'} - assert json.encode_pretty(foo) == '{ - "name": "Bob" -}' -} struct Foo3 { name string @@ -369,7 +358,7 @@ struct Foo3 { fn test_omit_empty() { foo := Foo3{'Bob', 0} assert json.encode_pretty(foo) == '{ - "name": "Bob" + "name": "Bob" }' }