Provides ability to determine if a json key has been set to null or not provided. Inspired by How to determine if a JSON key has been set to null or not provided article by Jon Calhoun
To get the package, execute:
go get gopkg.in/romanyx/nullable.v1
To import this package, add the following line to your code:
import "gopkg.in/romanyx/nullable.v1"
Refer to it as nullable
.
For more details, see the API documentation.
import "gopkg.in/romanyx/nullable.v1"
func main() {
usr := struct {
Name nullable.String `json:"name"`
}{}
data := []byte("{}")
if err := json.Unmarshal(data, &usr); err != nil {
log.Fatalf("unmarshaling failed: %s\n", err)
}
fmt.Println(usr.Name.Present) // false
fmt.Println(usr.Name.Valid) // false
fmt.Println(usr.Name.Value) // ""
data = []byte("{\"name\":null}")
if err := json.Unmarshal(data, &usr); err != nil {
log.Fatalf("unmarshaling failed: %s\n", err)
}
fmt.Println(usr.Name.Present) // true
fmt.Println(usr.Name.Valid) // false
fmt.Println(usr.Name.Value) // ""
data = []byte("{\"name\":\"John\"}")
if err := json.Unmarshal(data, &usr); err != nil {
log.Fatalf("unmarshaling failed: %s\n", err)
}
fmt.Println(usr.Name.Present) // true
fmt.Println(usr.Name.Valid) // true
fmt.Println(usr.Name.Value) // "John"
}
Please feel free to submit issues, fork the repository and send pull requests!