-2

I'm trying to parse the json below in go, but struggling to find the type or struct to decode into. I don't have any control over the format and the stocks returned might be different for each call, so I can't have a type named AAPL or TSLA. I ultimately want an array/list of objects with the data inside the 'quote' section. Something like:

type Stock struct {
  Symbol string
  CompanyName string
  latestPrice float64
}

Any thoughts?

{
  "AAPL": {
    "quote": {
      "symbol": "AAPL",
      "companyName": "Apple, Inc.",
      "open": 308,
      "close": 315.01,
      "high": 317.05,
      "low": 307.24,
      "latestPrice": 315.01,
      "marketCap": 1365360443400,
      "peRatio": 24.49,
      "week52High": 327.85,
      "week52Low": 170.27
    }
  },
  "TSLA": {
    "quote": {
      "symbol": "TSLA",
      "companyName": "Tesla, Inc.",
      "open": 790.51,
      "close": 811.29,
      "high": 824,
      "low": 785,
      "latestPrice": 811.29,
      "marketCap": 150389638590,
      "peRatio": -963.76,
      "week52High": 968.99,
      "week52Low": 176.99
    }
  }
}
Manish
  • 1,139
  • 7
  • 21

1 Answers1

5

First you have to export all your fields, then you can use a map whenever the field names are not known up front. After unmarshaling you can then range over the map and put the data to whatever other structure you would like.

type Stock struct {
    Symbol      string
    CompanyName string
    LatestPrice float64
}

func main() {
    var m map[string]struct{ Quote Stock }
    if err := json.Unmarshal(data, &m); err != nil {
        panic(err)
    }

    var list []Stock
    for _, v := range m {
        list = append(list, v.Quote)
    }

    fmt.Println(list)
}

https://play.golang.com/p/ZXlrWWWgxvB

mkopriva
  • 35,176
  • 4
  • 57
  • 71