1

With an http GET request I'm importing a JSON response into a string. I want to add the JSON string into a struct array with json.Unmarshal. This works only when I remove at the beginning the fields data & categoryGroups. They are not part of my strucs. So by removing {"data":{"categoryGroups": at the beginning and }} at the end.

This can be done with a strings.Replace, but I'm wondering if there is a neater solution?

{"data":{"categoryGroups":[{"name":"...."}]}]}}
2
  • 2
    In my opinion the best way is to just unmarshal into a matching structure and then ignore the undesired parts. For example: play.golang.org/p/tZHtt5hq-d3 Commented Mar 16, 2021 at 20:37
  • 1
    Thanks, this is indeed much better. Your code example really helped me!! Commented Mar 16, 2021 at 20:47

1 Answer 1

1

Based on suggestions from comments, I reproduced your scenario as follows:

package main

import (
    "encoding/json"
    "fmt"
)

var data = []byte(`{"data":{"categoryGroups":[{"name":"group1"}]}}`)

type CategoryGroup struct {
    Name string `json:"name"`
}

func main() {
    var v struct {
        Data struct {
            CategoryGroups []CategoryGroup `json:"categoryGroups"`
        } `json:"data"`
    }
    if err := json.Unmarshal(data, &v); err != nil {
        panic(err)
    }

    cgs := v.Data.CategoryGroups
    fmt.Println(cgs)
}

Output:

[{group1}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.