1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

json2: fix decode result with option fields (#17561)

This commit is contained in:
Felipe Pena 2023-03-08 16:54:28 -03:00 committed by GitHub
parent b19052949f
commit 785546f277
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 2 deletions

View File

@ -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"}'
}

View File

@ -154,6 +154,7 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
} }
} }
$for field in U.fields { $for field in U.fields {
mut ignore_field := false
value := val.$(field.name) value := val.$(field.name)
mut json_name := '' mut json_name := ''
for attr in field.attrs { for attr in field.attrs {
@ -219,6 +220,8 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
} $else { } $else {
return error('type ${typeof(val).name} cannot be array encoded') return error('type ${typeof(val).name} cannot be array encoded')
} }
} else {
ignore_field = true
} }
} $else { } $else {
is_none := val.$(field.name).str() == 'unknown sum type value' is_none := val.$(field.name).str() == 'unknown sum type value'
@ -345,11 +348,13 @@ 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)! wr.write(json2.comma_bytes)!
} }
if !ignore_field {
i++ i++
} }
}
e.encode_newline(level - 1, mut wr)! e.encode_newline(level - 1, mut wr)!
wr.write([u8(`}`)])! wr.write([u8(`}`)])!
} }