Using Interfaces with Golang Maps and Structs and JSON

21,952

I figured it out, I think..

package main

import (
    "encoding/json"
    "fmt"
)

type StatusType struct {
    Id     string            `json:"message_id,omitempty"`
    Status map[string]interface{} `json:"status,omitempty"`
}

func main() {
    var s StatusType
    s.Id = "12345"
    m := make(map[string]interface{})
    s.Status = m

    // Now this works
    // s.Status["x-value"] = "foo1234"
    // s.Status["y-value"] = "bar4321"

    // And this works
    sites := []string{"a", "b", "c", "d"}
    s.Status["site-value"] = sites

    var data []byte
    data, _ = json.MarshalIndent(s, "", "    ")

    fmt.Println(string(data))
}
Share:
21,952
jordan2175
Author by

jordan2175

Updated on December 31, 2020

Comments

  • jordan2175
    jordan2175 over 3 years

    I have some JSON code that can look like:

    {
        "message_id": "12345",
        "status_type": "ERROR",
        "status": {
            "x-value": "foo1234",
            "y-value": "bar4321"
        }
    }
    

    or can look like this. As you can see the "status" element changes from a standard object of strings to an object of array of strings, based on the status_type.

    {
        "message_id": "12345",
        "status_type": "VALID",
        "status": {
            "site-value": [
                "site1",
                "site2"
            ]
        }
    }
    

    I am thinking that I need to have my struct for "Status" take a map like "map[string]interface{}", but I am not sure exactly how to do that.

    You can see the code here on the playground as well.
    http://play.golang.org/p/wKowJu_lng

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type StatusType struct {
        Id     string            `json:"message_id,omitempty"`
        Status map[string]string `json:"status,omitempty"`
    }
    
    func main() {
        var s StatusType
        s.Id = "12345"
        m := make(map[string]string)
        s.Status = m
        s.Status["x-value"] = "foo1234"
        s.Status["y-value"] = "bar4321"
    
        var data []byte
        data, _ = json.MarshalIndent(s, "", "    ")
    
        fmt.Println(string(data))
    }