Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Interfaces with Golang Maps and Structs and JSON

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))
}
like image 471
jordan2175 Avatar asked Mar 16 '23 13:03

jordan2175


1 Answers

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))
}
like image 106
jordan2175 Avatar answered Mar 19 '23 22:03

jordan2175