Search code examples
jsongomarshallingunmarshalling

Golang Json marshalling


type Status struct {
 slug  string  `json:"slug"` 
}

type Instance struct {
  Slug   string                   `json:"slug"`
  Stat   map[string]*Status       `json:"status"`
 }

This Json response is recieved for API call:

    [ {
    "status": {
      "stop": false,
      "traffic": true,
      "label": null,
      "dead": true,
      "slug": "up",
    }, 
    "slug": "instances_raw",
    "started_at": "15120736198",
    "replacement": null
    },

    {
    "status": {
      "stop": false,
      "traffic": true,
      "label": null,
      "dead": true,
      "slug": "down",
     },
    "slug": "instance_raw2",
    "started_at": "1512073194",
    "replacement": null
   }
  ]

I am trying to marshall json into above struct but running into issue:

instances := make([]Instance, 0)
res := api call return above json
body, _ := ioutil.ReadAll(res.Body)
json.Unmarshal(body, &instances)
fmt.Println("I am struct %s",instances)

It is marshalling into:

I am struct %s [{ map[stop:0xc42018e1b0 dead:0xc42018e1e0 label:<nil> running:0xc42018e220 down:0xc42018e150 traffic:0xc42018e180]}]

Can someone help me figure out why it is not marshalling as I am expecting?

Expected marshalling:

[{instances_raw map[slug:up]} {instances_raw2 map[slug:down]}] 

Solution

  • The structs do not match the structure of the data. Perhaps you wanted this:

    type Status struct {
        Slug string `json:"slug"`
    }
    
    type Instance struct {
        Slug string `json:"slug"`
        Stat Status `json:"status"`
    }
    

    Output: [{instances_raw {up}} {instance_raw2 {down}}]

    run it on the plaground

    or this:

    type Instance struct {
        Slug string `json:"slug"`
        Stat map[string]interface{} `json:"status"`
    }
    

    Output: [{instances_raw map[label: dead:true slug:up stop:false traffic:true]} {instance_raw2 map[slug:down stop:false traffic:true label: dead:true]}]

    run it on the playground

    Always check errors. The example JSON above is not valid and the json.Unmarshal function reports this error.