简体   繁体   中英

Go json, marshal empty value

I'm having problems with omitempty and empty values. Please see this playground example . I have a value which I don't want to be ignored during marshal in case of value "" . This explicitly means that I want to clear the value and therefore I want to have marshalled result:

{"cf_objectType":"Product","cf_isLocked":"No","cf_ErrorMessage":""}

Now I tried the pointer-to-string approach here , but for some reason I don't like this. Are there any alternatives known? For example, why don't we have a tag (just like omitempty ) like omitnull or something?

EDIT

To clarify, see below

m := Metadata{
    ObjectType:   "Product",
    Locked:       "No",
    ErrorMessage: "",

}

I want the result of the marshal function on this struct to be:

{
    "cf_objectType":"Product",
    "cf_isLocked":"No",
    "cf_ErrorMessage":""
}

AND

m := Metadata{
    ObjectType:   "Product",
    Locked:       "No",
}

result shoulde be:

{
    "cf_objectType":"Product",
    "cf_isLocked":"No",
}

If you don't want to omit empty values, just remove omitempty tag

https://play.golang.org/p/6axA2OIG6O

With regard to your last comment (for which I don't have enough reputation to reply to):

Ok, this works: play.golang.org/p/TYk67p6i_b But then I have a mix of string and *string in my struct definition. And I also can't "fill" the value without having the var emptyString = "" , right?

See this (Golang: set nil string pointer to empty string) post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM