[Golang] I want to add omitempty to the json tag of the int type field of the structure so that it will be ignored if 0 is entered.

Introduction

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.

solution

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.

reference

-Play with JSON in go language-Qiita

Recommended Posts

[Golang] I want to add omitempty to the json tag of the int type field of the structure so that it will be ignored if 0 is entered.
I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python
I created a script to check if English is entered in the specified position of the JSON file in Python.
I want to initialize if the value is empty (python)
I want to know the legend of the IT technology world
I tried to expand the database so that it can be used with PES analysis software
I want to receive the configuration file and check if the JSON file generated by jinja2 is a valid JSON
I don't want to admit it ... The dynamical representation of Neural Networks
I didn't understand the behavior of numpy's argsort, so I will summarize it.
I want to identify the alert email. --Is that x a wildcard? ---
I want to read CSV line by line while converting the field type (while displaying the progress bar) and process it.