6

I get an response body. the format of the body is as below:

  [
    {
       "id":1,
       "name":"111" 
    },
    {
       "id":2,
       "name":"222" 
    }
  ]

I want to parse the body to json struct, my code is as below:

type Info struct {
      Id uint32 `json:id`
      Name string `json:name`
  }

  type Response struct {
      infos []Info
  }

  v := &Response{}
  data, err := ioutil.ReadAll(response.Body)
  if err := json.Unmarshal(data, v); err != nil {
      log.Fatalf("Parse response failed, reason: %v \n", err)
  }

It always give an error:cannot unmarshal array into Go value of type xxx, can someone give a help?

1
  • 4
    Do json.Unmarshal(data, &v.infos). If json is an array, you need to pass in a Go slice, if it's an object you need to pass in a Go struct, or map. Commented Oct 17, 2019 at 13:37

2 Answers 2

17

I actually stumbled upon this question while googling entry-level Go questions, so I figured I'd leave a message:

package main

import (
        "encoding/json"
        "fmt"
        "net/http"
)

func main() {
        url := "https://skishore.github.com/inkstone/all.json"

        resp, err := http.Get(url)
        if err != nil {
                panic(err)
        }
        defer resp.Body.Close()

        var j interface{}
        err = json.NewDecoder(resp.Body).Decode(&j)
        if err != nil {
                panic(err)
        }
        fmt.Printf("%s", j)
}

This downloads an example JSON url, decodes it without any prior knowledge of its contents and prints to stdout. Keep in mind that it would be better to actually assign a type of some kind.

Sign up to request clarification or add additional context in comments.

Comments

0

This is the wrong type for the response:

  type Response struct {
      infos []Info
  }

First, infos is not public, so json marshalers will ignore it. But more importantly, the input is not a struct or json object, it is a slice or json array. Changing Response to a slice results in:

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

func main() {

    data := []byte(`
  [
    {
       "id":1,
       "name":"111" 
    },
    {
       "id":2,
       "name":"222" 
    }
  ]
`)

    type Info struct {
        Id   uint32 `json:"id"`
        Name string `json:"name"`
    }

    type Response []Info

    v := &Response{}
    if err := json.Unmarshal(data, v); err != nil {
        log.Fatalf("Parse response failed, reason: %v \n", err)
    }

    fmt.Printf("%#v\n", v)
}

Which can be verified in the Go playground.

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.