json and 'omitempty'

659 views
Skip to first unread message

Alexander Sychev

unread,
Jan 26, 2012, 4:29:11 AM1/26/12
to golan...@googlegroups.com
Hello!

I have found an unexpected by me behaviour of the 'omitempty' option in
the json package.


The field SomeA of the structure B is the structure with unexported
fields, so SomeA can't be marshaled to JSON. The SomeA has the option
'omitempty' and I expect the SomeA won't appear in resulting JSON. But it
does appear.

This is a bug? Or a feature?

-- 
Best regards,
    santucco

roger peppe

unread,
Jan 26, 2012, 5:57:46 AM1/26/12
to Alexander Sychev, golan...@googlegroups.com

i think this is within spec. the docs say:
"The empty values are false, 0, any nil pointer or interface value,
and any array, slice, map, or string of length zero"

that doesn't include structs, so i think the above behaviour is correct.

it could be argued that a zero-valued struct should be considered empty,
especially now that structs are comparable. but that would be an API change.

for the time being, you could use *A instead of A.

Alexander Sychev

unread,
Jan 26, 2012, 7:44:29 AM1/26/12
to roger peppe, golan...@googlegroups.com
Thanks!

Actually I found this in GAE, where new option 'omit' is not yet
presented, so I have hoped 'omitempty' for such case can help.


--
Best regards,

Alexander Sychev
Senior Developer
Kaspersky Lab

10/1, 1st Volokolamsky Proezd
Moscow 123060
Russia

Alexande...@kaspersky.com
T/F: +7 495 797 87 00
D: +7 495 797 87 00 x1371
M: +7 916 967 63 93


www.kaspersky.com
www.securelist.com

Reply all
Reply to author
Forward
0 new messages