Home >Backend Development >Golang >json.Unmarshal Convert to another custom type (mapped to slice)
php editor Apple will introduce you to how to use the json.Unmarshal function to convert JSON data into another custom type, that is, mapped to slices. During the development process, we often encounter situations where we need to convert JSON data into different data types, and the json.Unmarshal function can help us achieve this function. Through the introduction and sample code of this article, I believe readers can better understand and apply the json.Unmarshal function and improve development efficiency and code quality.
Given the following json string:
{ "username":"bob", "name":"robert", "locations": [ { "city": "paris", "country": "france" }, { "city": "los angeles", "country": "us" } ] }
I need a way to unmarshal it into a structure like this:
type User struct { Username string Name string Cities []string }
Where cities
is a slice containing the "city" value, "country" is discarded.
I think this can be done using a custom json.unmarshal
function, but not sure how.
You can define new types for cities
and implement custom unmarshaler:
type User struct { Username string `json:"username"` Name string `json:"name"` Cities []Cities `json:"locations"` } type Cities string func (c *Cities) UnmarshalJSON(data []byte) error { tmp := struct { City string `json:"city"` }{} err := json.Unmarshal(data, &tmp) if err != nil { return err } *c = Cities(tmp.City) return nil }
The above is the detailed content of json.Unmarshal Convert to another custom type (mapped to slice). For more information, please follow other related articles on the PHP Chinese website!