mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
x.json2: add encode_pretty/1 (#16634)
This commit is contained in:
parent
4b2699fddd
commit
e8c0b098b0
@ -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()
|
||||
|
@ -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 {
|
||||
|
@ -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"
|
||||
}'
|
||||
}
|
||||
|
@ -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"
|
||||
}'
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user