How to Unmarshal a JSON String into a Slice Using a Delimiter in Golang?

Linda Hamilton
Release: 2024-10-26 21:52:02
Original
235 people have browsed it

How to Unmarshal a JSON String into a Slice Using a Delimiter in Golang?

Custom Unmarshal with String Split in Golang

Problem:

Unmarshalling JSON into a struct with a field that should be a slice of strings, while the JSON value is a single string that needs to be split using a delimiter.

<code class="json">{
  "student_number": 1234567,
  "name": "John Doe",
  "subjects": "Chemistry-Maths-History-Geography"
}</code>
Copy after login
<code class="go">type Student struct {
  StudentNumber int
  Name          string
  Subjects      []string
}</code>
Copy after login

Answer:

Define a custom string slice type and implement json.Unmarshaler to handle the split:

<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>
Copy after login

Use this custom type in the struct:

<code class="go">type Student struct {
  StudentNumber int
  Name          string
  Subjects      strslice
}</code>
Copy after login

Code Example:

<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>
Copy after login

Output:

{1234567 John Doe [Chemistry Maths History Geography]} <nil>
Copy after login

The above is the detailed content of How to Unmarshal a JSON String into a Slice Using a Delimiter in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!