乐闻世界logo
搜索文章和话题

How to insert null value in JSON type in golang

1个答案

1

In Go, handling JSON typically involves the encoding/json package. When representing null values in JSON, pointers are often used because in Go, basic types like int and string cannot be assigned null by default; they have their own zero values (e.g., the zero value for int is 0, and for string is the empty string ""). Using pointers allows these fields to be serialized as null in JSON.

Example

Suppose we have a struct representing user information, where some fields may be null values:

go
type User struct { Name *string `json:"name"` Age *int `json:"age"` Email *string `json:"email"` }

Inserting Null Values

When creating a new User instance and wanting a field to appear as null in JSON, we can do the following:

go
func main() { var name *string // default nil age := new(int) // create a pointer to the zero value of int *age = 30 // set Age to 30 user := User{ Name: name, // Name is nil, so it appears as null in JSON Age: age, // Age is not nil, so it appears as its value Email: nil, // Email is nil, so it appears as null in JSON } userData, err := json.Marshal(user) if err != nil { fmt.Println("Error:", err) } fmt.Println(string(userData)) // Output: {"name":null,"age":30,"email":null} }

Explanation

In this example:

  • The Name and Email fields are set to nil, so they appear as null in JSON.
  • Although Age is also a pointer, we create a pointer to the zero value of int using new(int) and set its value to 30, so it appears as 30 in JSON.

By using pointers, we can accurately represent whether a value exists in JSON (i.e., distinguish between zero values and null). This is particularly useful when handling HTTP requests and responses, as it allows distinguishing between unset values and values set to zero.

2024年8月12日 18:41 回复

你的答案