dingrui
dingrui

Reputation: 507

How to parse http response body to json format in golang?

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?

Upvotes: 6

Views: 28219

Answers (1)

d33tah
d33tah

Reputation: 11561

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.

Upvotes: 16

Related Questions