Battalgazi
Battalgazi

Reputation: 379

Unmarshall JSON with a [int]string map contained in an array

Im trying to unmarshall the following JSON into a struct, but there I am unable to translate the contents of the values field with the [[int,string]] This is what I have so far:

type Response struct {
            Metric struct {
                Name string `json:"name,omitempty"`
                Appname string `json:"appname,omitempty"`
            } `json:"metric,omitempty"`
            Values []map[int]string `json:"values,omitempty"`
}

The JSON file:

{
   "metric":{
      "name":"x444",
      "appname":"cc-14-471s6"
   },
   "values":[
      [
         1508315264,
         "0.0012116165566900816"
      ],
      [
         1508315274,
         "0.0011871631158857396"
      ]
   ]
}

Upvotes: 0

Views: 61

Answers (1)

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6278

The data you showed should be unmarshaled to:

type Response struct {
            Metric struct {
                Name string `json:"name,omitempty"`
                Appname string `json:"appname,omitempty"`
            } `json:"metric,omitempty"`
            Values [][]interface{} `json:"values,omitempty"`
}

If you want to to transfer it to map implement json.Unmarshaller interface - https://golang.org/pkg/encoding/json/#Unmarshaler

You can have something like:

type Item struct {
    Key int
    Val string
}
func(item *Item) UnmarshalJSON([]byte) error {
    // TODO: implement 
}

type Response struct {
            Metric struct {
                Name string `json:"name,omitempty"`
                Appname string `json:"appname,omitempty"`
            } `json:"metric,omitempty"`
            Values []Item  `json:"values,omitempty"`
}

Upvotes: 1

Related Questions