json: encode_pretty (p. 2) + tests

pull/8672/head
Alexander Medvednikov 2021-02-10 10:17:29 +01:00
parent f67e4ab57c
commit 035a163454
2 changed files with 21 additions and 14 deletions

View File

@ -160,7 +160,7 @@ fn test_struct_in_struct() {
fn test_encode_map() { fn test_encode_map() {
expected := '{"one":1,"two":2,"three":3,"four":4}' expected := '{"one":1,"two":2,"three":3,"four":4}'
numbers := { numbers := map{
'one': 1 'one': 1
'two': 2 'two': 2
'three': 3 'three': 3
@ -172,7 +172,7 @@ fn test_encode_map() {
} }
fn test_parse_map() { fn test_parse_map() {
expected := { expected := map{
'one': 1 'one': 1
'two': 2 'two': 2
'three': 3 'three': 3
@ -180,7 +180,7 @@ fn test_parse_map() {
} }
out := json.decode(map[string]int, '{"one":1,"two":2,"three":3,"four":4}') or { out := json.decode(map[string]int, '{"one":1,"two":2,"three":3,"four":4}') or {
assert false assert false
r := { r := map{
'': 0 '': 0
} }
r r
@ -201,18 +201,14 @@ fn test_nested_type() {
countries: [ countries: [
Country{ Country{
name: 'UK' name: 'UK'
cities: [City{'London'}, cities: [City{'London'}, City{'Manchester'}]
City{'Manchester'},
]
}, },
Country{ Country{
name: 'KU' name: 'KU'
cities: [City{'Donlon'}, cities: [City{'Donlon'}, City{'Termanches'}]
City{'Termanches'},
]
}, },
] ]
users: { users: map{
'Foo': User{ 'Foo': User{
age: 10 age: 10
nums: [1, 2, 3] nums: [1, 2, 3]
@ -230,14 +226,14 @@ fn test_nested_type() {
pets: 'little boo' pets: 'little boo'
} }
} }
extra: { extra: map{
'2': { '2': map{
'n1': 2 'n1': 2
'n2': 4 'n2': 4
'n3': 8 'n3': 8
'n4': 16 'n4': 16
} }
'3': { '3': map{
'n1': 3 'n1': 3
'n2': 9 'n2': 9
'n3': 27 'n3': 27
@ -379,3 +375,14 @@ fn test_decode_null_object() {
assert '$info.items' == '[]' assert '$info.items' == '[]'
assert '$info.maps' == '{}' assert '$info.maps' == '{}'
} }
struct Foo2 {
name string
}
fn test_pretty() {
foo := Foo2{'Bob'}
assert json.encode_pretty(foo) == '{
"name": "Bob"
}'
}

View File

@ -629,7 +629,7 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
is_json_encode := name == 'json.encode' is_json_encode := name == 'json.encode'
is_json_encode_pretty := name == 'json.encode_pretty' is_json_encode_pretty := name == 'json.encode_pretty'
is_json_decode := name == 'json.decode' is_json_decode := name == 'json.decode'
g.is_json_fn = is_json_encode || is_json_decode g.is_json_fn = is_json_encode || is_json_encode_pretty || is_json_decode
mut json_type_str := '' mut json_type_str := ''
mut json_obj := '' mut json_obj := ''
if g.is_json_fn { if g.is_json_fn {