Home >Backend Development >Golang >How to Split a JSON Field into a String Slice During Unmarshaling in Golang?
Custom Unmarshal with String Split in Golang
Problem:
Handling JSON unmarshalling when one field requires splitting into a slice using string operations. Specifically, the "subjects" field in the provided JSON requires splitting on '-' to create a []string.
Solution:
To achieve this, we can define a custom string slice type and implement the json.Unmarshaler interface for it. Here's how:
<code class="go">type strslice []string func (ss *strslice) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return err } *ss = strings.Split(s, "-") return nil }</code>
This custom type will allow us to unmarshal the "subjects" field as a string and then automatically split it into a slice.
Revised Struct:
Now, we can update our Student struct to use the custom strslice type for the "subjects" field:
<code class="go">type Student struct { StudentNumber int `json:"student_number"` Name string `json:"name"` Subjects strslice `json:"subjects"` }</code>
Usage:
With these modifications, we can now unmarshal the provided JSON and have the "subjects" field automatically split:
<code class="go">func main() { var s Student err := json.Unmarshal([]byte(src), &s) fmt.Println(s, err) } const src = `{"student_number":1234567, "name":"John Doe", "subjects":"Chemistry-Maths-History-Geography"}`</code>
Output:
{1234567 John Doe [Chemistry Maths History Geography]} <nil>
This approach provides a clean and customizable way to handle field transformations while unmarshalling JSON data.
The above is the detailed content of How to Split a JSON Field into a String Slice During Unmarshaling in Golang?. For more information, please follow other related articles on the PHP Chinese website!