In golang, I want to ignore json when the value of the int type field of the structure is 0.
In other words, if you specify `ʻomitemptyin the json tag of an int type field and
0`` is entered in the value of that field, you want to ignore it.
** * Addition ** ** Is it actually more appropriate to say "null" than "ignore"? **
omitempty
I figured out how to ignore json when the struct field is empty
type User struct {
Name string `json:"name, omitempty"`
Age int64 `json:"age, omitempty"`
}
However, in `ʻomitempty, the numeric type cannot be ignored even if
0`` is entered.
So, if you want to use a numeric field as a pointer and ignore it, you can solve it by putting nil in the pointer.
//User structure
type User struct {
Name string `json:"name, omitempty"`
Age *int64 `json:"age, omitempty"`
}
//Value to map to the structure
testName := "Alice"
testAge := 20
var age *int64
if age > 0 {
age = &testAge
} else {
age = nil
}
user := User {
Name: testName,
Age: age,
}
If you do the above, when you make json.Marshal (user)
,
~~ If testAge
is 0
, the ʻAge`` field of the
ʻUserstructure is ignored, If it is greater than
0, it will not be ignored. ~~ If
testAgeis
0, then json will be
"age": null When it is larger than
0, it becomes
"age": 20`` and so on.
-Play with JSON in go language-Qiita
Recommended Posts