Andrew Samuelsen
Andrew Samuelsen

Reputation: 5432

Accessing data in nested arrays & objects with Go

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.

Upvotes: 2

Views: 1515

Answers (1)

Henry Finucane
Henry Finucane

Reputation: 714

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

Upvotes: 1

Related Questions