2

I'm doing my best to unmarshall some json data into usable form in Go, but can't seem to get it. The data is:

{
    "series": [
        {
            "series_id": "PET.EMD_EPD2D_PTE_NUS_DPG.W",
            "name": "U.S. No 2 Diesel Retail Prices, Weekly",
            "units": "Dollars per Gallon",
            "updated": "2013-09-27T07:21:57-0400",
            "data": [
                [
                    "20130923",
                    "3.949"
                ],
                [
                    "20130916",
                    "3.974"
                ]
            ]
        }
    ]
}

I'm trying to get the arrays under data into a variable, so I can loop through them and do something like:

if data[i][0] == "20130923" {
    fuelPrice.Price == data[i][1]
}

I've tried to unmarshall the data into a struct but I can't figure out how to get past series... ie I can't figure out how to do nested arrays. Things like these don't work:

type Series struct {
    SeriesId    string
    Name        string
    Data        [][]string
}

type RawFuelPrice struct {
    Series []Series
    Data []interface{}[]
}

Also if I unmarshal into an interface{}, I can't figure out how to access the data...

I'm definitely a beginner. Thanks for your time and effort.

Andrew Samuelsen
  • 5,325
  • 9
  • 47
  • 69
  • See e.g. http://stackoverflow.com/questions/19145202/marshal-of-json-rawmessage http://stackoverflow.com/questions/19088799/go-xml-parsing-doesnt-see-any-fields http://stackoverflow.com/questions/19081479/xml-decoding-in-go http://stackoverflow.com/questions/18806325/json-decoder-gives-unexpected-results and of course http://golang.org/pkg/encoding/json/#pkg-examples . XML and JSON decoding works pretty much the same, just use `json:"xyz"` as struct tag. – Volker Oct 02 '13 at 20:57
  • @Volker, sorry but I just am not able to figure this out. I've tried this: `type EIASeries []struct { SeriesId string `json:"series_id"` Data interface{} `json:"data"` } type EIAResponse struct { Series EIASeries `json:"series"` }` When I log the var resp EIAResponse, I get a lot of data, but I can't get anything when I log resp.Series or log resp.Series.Data... Thanks. – Andrew Samuelsen Oct 02 '13 at 22:03
  • Maybe http://play.golang.org/p/CZFFWMIdoG is what you want. – Volker Oct 02 '13 at 22:35

1 Answers1

1

Your code is just fine- except for the Data member of the RawFuelPrice struct. I don't think that syntax is valid, and there's no Data attribute at the top level of of the JSON blob.

That said, this is how you'd get the data out:

var rfp RawFuelPrice
json.Unmarshal(input, &rfp)
for _,s := range rfp.Series {
    fmt.Println("Name",s.Name)
    for _,d := range s.Data {
        fmt.Println("\tdate:",d[0])
        fmt.Println("\tprice:",d[1])
    }
    fmt.Println()
}

Although you'd probably want to check that all the data was there.

Go Playground link: http://play.golang.org/p/C47lZJ_L0o

Henry Finucane
  • 704
  • 3
  • 12