Code Json to Struct in Go

Hi friends! I want save the code Json to my struct. The code is:

{
“Dogs”: [
{
“name”: “Alma”,
“year_old”: 2,
“Description”: [“This”, “is”, “Description”, “in”, “a”, “Vector1”]
},
{
“name”: “Tobby”,
“year_old”: 4,
“Description”: [“This”, “is”, “Description”, “in”, “a”, “Vector2”]
}
}

My class is defined as:

type Dog struct {
Name string json:"name"
Year_old float32 json:"year_old"
Description []string json:"description"

}

I try make the next code but the var dogs is nil:

func getDogs(w http.ResponseWriter, r *http.Request) {
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, “error”)
return
}

var dogs []Dog
json.Unmarshal(reqBody, &dogs)

The problem is the array “Dogs: []” in the Json. If remove “Dogs: []”, the var dogs conteins the two objetcs.

Thank you.
Bye friends.
Sorry for my basic english.

Your JSON does not contain an array but a single object that has a member named Dogs whose value is an array. You will have to represent this in your code.

type Dog struct {
	Name        string   `json:"name"`
	Year_old    float32  `json:"year_old"`
	Description []string `json:"description"`
}

type Dogs struct {
	Dogs []Dog `json:"Dogs"`
}

func main() {
	var dogs Dogs
	json.Unmarshal([]byte(j), &dogs)

	fmt.Println(dogs)
}

See https://play.golang.org/p/Nqxl-S4Pqn9

2 Likes

Hi! dogs return nil. I did exactly what you mention, only i replace j for reqBody:

reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, “error en datos enviados”)
return
}

Check the error of unmarschal, what does it say?

In general, for debugging at least, it’s always a good idea to log full returned error and also the data that might lead to that error.

In general, whenever a function or method returns an error value, you should check it, though Lutz left that off in his example.

2 Likes

Sorry, I had this:

func main() {

var dogs []Dogs <--------------------  error is Dogs

json.Unmarshal([]byte(j), &dogs)

fmt.Println(dogs)

}

Thank you!!!

I’m not sure what you mean by that last post, sorry.

Does it work now?

Are you sure that reqBody contains the JSON you expect? If yes, the code I’ve shown above should work. If no, what exactly does the request body contain?

Use this online tools which Converts JSON to struct in Go