From d00808660f18daee71d7ba3efded7a95cd4a937c Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Thu, 16 Sep 2021 07:02:43 +0300 Subject: [PATCH] json: omitempty --- vlib/json/json_test.v | 14 ++++++++++++++ vlib/v/gen/c/json.v | 8 ++++++++ 2 files changed, 22 insertions(+) diff --git a/vlib/json/json_test.v b/vlib/json/json_test.v index ca6b2ac3e7..1c9f5b4496 100644 --- a/vlib/json/json_test.v +++ b/vlib/json/json_test.v @@ -366,3 +366,17 @@ fn test_pretty() { "name": "Bob" }' } + +struct Foo3 { + name string + age int [omitempty] +} + +fn test_omit_empty() { + foo := Foo3{'Bob', 0} + assert json.encode_pretty(foo) == '{ + "name": "Bob" +}' + // println('omitempty:') + // println(json.encode_pretty(foo)) +} diff --git a/vlib/v/gen/c/json.v b/vlib/v/gen/c/json.v index cfc480dea5..5a45420517 100644 --- a/vlib/v/gen/c/json.v +++ b/vlib/v/gen/c/json.v @@ -117,6 +117,8 @@ fn (mut g Gen) gen_struct_enc_dec(type_info ast.TypeInfo, styp string, mut enc s mut is_raw := false mut is_skip := false mut is_required := false + mut is_omit_empty := false + for attr in field.attrs { match attr.name { 'json' { @@ -131,6 +133,9 @@ fn (mut g Gen) gen_struct_enc_dec(type_info ast.TypeInfo, styp string, mut enc s 'required' { is_required = true } + 'omitempty' { + is_omit_empty = true + } else {} } } @@ -184,6 +189,9 @@ fn (mut g Gen) gen_struct_enc_dec(type_info ast.TypeInfo, styp string, mut enc s } // Encoding mut enc_name := js_enc_name(field_type) + if is_omit_empty { + enc.writeln('\t if (val.${c_name(field.name)} != ${g.type_default(field.typ)}) \n') + } if !is_js_prim(field_type) { if field_sym.kind == .alias { ainfo := field_sym.info as ast.Alias