Connor
Connor

Reputation: 423

Unmarshalling Json data into map in Go

I am dealing with an api that returns json data such as:

    {
  "bpi": {
    "2018-06-01": 128.2597,
    "2018-06-02": 127.3648
  },
  "disclaimer": "something here.",
  "time": {
    "updated": "Sep 6, 2013 00:03:00 UTC",
    "updatedISO": "2013-09-06T00:03:00+00:00"
  }

However the price data that has the accompanying dates can return a dynamic date range (ie could be anything from 1 data pair to 1000).

I'm trying to take only the date and price pairs and put them into a map for later consumption, but I'm not finding a straight forward way of doing it. When I put this into a json-to-go auto struct generator it will create a statically and named struct for the pricing.

This is my best attempt at handling the data dynamically. I am passing an empty interface from the response body of the http get, specifically:

var unstructuredJSON interface{} json.Unmarshal(body, &unstructuredJSON)

and passing the unstructuredJSON to the function:

func buildPriceMap(unstructuredJSON interface{}, priceMap map[string]float64) {
jsonBody := unstructuredJSON.(map[string]interface{})

for k, v := range jsonBody {
    switch vv := v.(type) {
    case string:
        // Do Nothing
    case float64:
        priceMap[k] = vv
    case interface{}:
        buildPriceMap(vv, priceMap)
    default:
        log.Fatal("Json unknown data handling unmarshal error: ", k, vv)
    }
}

Is there a better way to do this?

Upvotes: 0

Views: 115

Answers (1)

Zak
Zak

Reputation: 5898

Assuming that you know the top level keys, e.g. bpi, disclaimer, time etc and that the "dynamic data pairs" that you are talking about are part of the bpi field, and that the key and value types of each of the members of bpi are always string: decimal number you do something like....

type APIResp struct {
    BPI        map[string]float64 `json:"bpi"`
    Disclaimer string
    // other fields
}

Now each of your pairs will be typed correctly and contained in the APIResp.BPI map. Unmarshal as you are doing already;

var r APIResp
err := json.Unmarshal(body, &r)
// TODO: check err

Upvotes: 1

Related Questions