diff --git a/vlib/x/json2/encode_option_test.v b/vlib/x/json2/encode_option_test.v new file mode 100644 index 0000000000..505303c83c --- /dev/null +++ b/vlib/x/json2/encode_option_test.v @@ -0,0 +1,13 @@ +import x.json2 + +struct JoseHeader { +pub mut: + cty ?string + alg string + typ string = 'JWT' +} + +fn test_main() { + res := json2.encode(JoseHeader{ alg: 'HS256' }) + assert res == '{"alg":"HS256","typ":"JWT"}' +} diff --git a/vlib/x/json2/encoder.v b/vlib/x/json2/encoder.v index 6b8c1c6378..0eff6a24d8 100644 --- a/vlib/x/json2/encoder.v +++ b/vlib/x/json2/encoder.v @@ -154,6 +154,7 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! { } } $for field in U.fields { + mut ignore_field := false value := val.$(field.name) mut json_name := '' for attr in field.attrs { @@ -219,6 +220,8 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! { } $else { return error('type ${typeof(val).name} cannot be array encoded') } + } else { + ignore_field = true } } $else { is_none := val.$(field.name).str() == 'unknown sum type value' @@ -345,10 +348,12 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! { } } - if i < fields_len - 1 { + if i < fields_len - 1 && !ignore_field { wr.write(json2.comma_bytes)! } - i++ + if !ignore_field { + i++ + } } e.encode_newline(level - 1, mut wr)! wr.write([u8(`}`)])!