0

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",
}
4
  • which json do you want to get as a result? if you delete omitempty for ErrorMessage you'll get: {"cf_objectType":"Product","cf_isLocked":"No","cf_errorMessage":""} Is it what you need? Commented Jul 27, 2017 at 10:38
  • See me edit, which illustrates a bit more. Commented Jul 27, 2017 at 12:54
  • The problem is, ErrorMessage is implicitly initialized to its zero value, "". So the two examples are feeding identical data into Marshal, so they will always yield identical output. If you don't like using a *string (though you don't state why), then even if there were an omitnil, it wouldn't help - you can't have a nil string, only a nil pointer, so you would still need to use a pointer to a string. Commented Jul 27, 2017 at 13:43
  • 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? Commented Jul 27, 2017 at 17:25

2 Answers 2

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.