Assigning null to JSON fields instead of empty strings

后端 未结 5 1902
迷失自我
迷失自我 2020-11-29 23:34

Since empty string is the zero/default value for Go string, I decided to define all such fields as interface{} instead. for example



        
5条回答
  •  一生所求
    2020-11-30 00:34

    For the case of a json object with null strings, its easiest to use the omitempty decorator on the field.

    type student struct {
      FirstName  string `json:"first_name,omitempty"`
      MiddleName string `json:"middle_name,omitempty"`
      LastName   string `json:"last_name"`
    }
    

    With the above declaration, only if first_name was assigned will that key show up in the resultant json. last_name, on the otherhand, will always show up in the result with a value of "" if not assigned.

    Now when you start including numeric fields where 0 could be a value, using omitempty doesn't do what one would expect. A 0 value always drops the field, and we need to be able to differentiate between a 0 value and an unassigned value. Here use of library such as https://github.com/guregu/null may be advisable.

    More discussion here: https://www.sohamkamani.com/blog/golang/2018-07-19-golang-omitempty/

提交回复
热议问题