0

So basically, I'm trying to parse a JSON and assign its values to a struct. I get no errors when I run this, but the returned struct yeilds {0 0 0} which is incorrect. I tried putting in a fake url to see if there was just a connection issue, but that doesn't seem to be the case.

Since Go isn't asynchronous, there shouldn't be a problem with just calling things sequentially, right?

Here's the JSON I hosted on some site

{"ability":5335,"time":338,"level":1}

Here's the code

package main

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

type prog struct {
    ability int64
    time    int64
    level   int64
}

func main() {
    url := "https://api.myjson.com/bins/2c54h"

    //get the data from the url
    res, err := http.Get(url)
    //error handling
    defer res.Body.Close()

    if err != nil {
        panic(err)
    }

    // read json response
    data, err := ioutil.ReadAll(res.Body)
    // error handling
    var jsonData prog
    err = json.Unmarshal([]byte(data), &jsonData)

    if err != nil {
        panic(err)
    }

    //test struct data
    fmt.Println(jsonData)
}

The JSON is here

Maz Baig
  • 87
  • 1
  • 8

3 Answers3

0

Rename the fields of your struct so that they start with capital letters, and it should work.

If necessary, also append a hint at the end of each field name, using backticks.

Mike Spear
  • 832
  • 8
  • 13
0

The fields in your struct must be exported (start with a capital letter) for the JSON package to be able to see them.

type prog struct {
    Ability int64
    Time    int64
    Level   int64
}

See http://play.golang.org/p/yjtth5kliB for an example.

The fact you're downloading the data before the JSON parsing is unrelated to what you're seeing.

djd
  • 4,988
  • 2
  • 25
  • 35
0

You almost had it. You just need to change the way you declare your struct to include capital letters (otherwise they won't be exported) and specify that the json uses lowercase names.

type prog struct {
    Ability int64 `json:"ability"`
    Time    int64 `json:"time"`
    Level   int64 `json:"level"`
}
njachowski
  • 927
  • 5
  • 14
  • Any reason why they do that? – Maz Baig Jan 14 '16 at 06:26
  • My understanding is that it is golang law/convention to only expose capitalised names. Since json convention is to use lowercase naming you will often see this syntax in structs that need to deal with json. Feel free to upvote this answer if you found it at all useful. Thanks! – njachowski Jan 14 '16 at 06:41