-3

when parsing after a get request, how would I grab the 'personaname' and 'realname' values? the way I'm doing it with this struct

type Response struct {
    personaname string
    realname string
}

and this code

sb := string(res.Body())
var response []Response
json.Unmarshal([]byte(sb), &response)

isn't giving me anything. any tips? I'm not really familiar with json and how this kind of json works. (below is the response json)

{
  "response": {
    "players": [
      {
        "personaname": "alfred",
        "realname": "alfred d"
      },
      {
        "personaname": "EJ",
        "realname": "Erik Johnson"
      }
    ]
  }
}
tanpug
  • 1

2 Answers2

3

You need to define a full structure that matches the JSON, partially or totally but from the root.

https://play.golang.org/p/I8fUhN4_NDa

package main

import (
    "encoding/json"
    "fmt"
)

type Body struct {
    Response struct {
        Players []Player
    }
}

type Player struct {
    PersonaName string
    Realname    string
}

func main() {

    body := []byte(`{
          "response": {
            "players": [
              {
                "personaname": "alfred",
                "realname": "alfred d"
              },
              {
                "personaname": "EJ",
                "realname": "Erik Johnson"
              }
            ]
          }
        }`)

    var parsed Body
    if err := json.Unmarshal(boddy, &parsed); err != nil {
        panic(err)
    }

    fmt.Printf("%+v", parsed.Response.Players)

}
wakumaku
  • 616
  • 5
  • 5
-1

Actually your structure won't work since you body request is an array of objects. With this structure you wait for body like this{ "personaname": "alfred", "realname": "alfred d"} with just one object.

I recommend you to create a new structure that takes a slice pointing to your structure response. You would have like

   type Response struct {
    Personaname string
    Realname string
   }
    
    type Rsp struct {

        Players []Response `json:"players"`
    }