Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unmarshal ignore empty fields

I get a JSON from a client on the successful submit of user details.

Some element in the JSON can be skipped since they were not updated.

On the Go server side, I have an equivalent struct defined.

The server successfully marshals the JSON bytes into the struct.

type user struct {
    Id       *int64  `json:",omitempty"`
    Name     *string `json:",omitempty"`
    Age      *int64  `json:",omitempty"`
}

But for fields which are not recieved from client, unmarshal by default hard-codes nil for string and empty array for string array.

For example, if I get the json { "Id" : 64, "Name" : "Ryan" },
I don't want unmarshal to convert it to {"Id" : some hexadecimal, "Name" : some hexadecimal, "Age" : nil}.
To make it simple, I would expect it to be {"Id" : some hexadecimal, "Name" : some hexadecimal }

How can I totally ignore the field and map what I get?

Goplayground Code : http://play.golang.org/p/3dZq0nf68R

like image 981
connectwithpalaniappan Avatar asked Aug 05 '14 00:08

connectwithpalaniappan


1 Answers

You are a little bit confused, fmt.Printf("%+v", animals) prints the Go structs, which will always have all fields specified printed out.

However, if you convert it back to json, it will omit the nil fields.

Check http://play.golang.org/p/Q2M5oab2UX

like image 81
OneOfOne Avatar answered Nov 13 '22 02:11

OneOfOne