Search code examples
arraysjsongostructmarshalling

Create heterogeneous json array in go


Suppose I have an struct like this in go:

type Message struct {
    Args   []interface{}
    Kwargs map[string]interface{}
}

message := Message{                                                                                                                                                                                            
    []interface{}{1, 2, 3, 4},                                                                                                                                                                                 
    map[string]interface{}{"a": 2, "b": 3},                                                                                                                                                                    
}

How should I marshal message to have a JSON like this?

[[1,2,3,4], {"a": 2, "b":3}]

Solution

  • You can add a marshal method to your struct to handle the logic. Something in the lines of

    func (m Message) MarshalJSON() ([]byte, error) {
        data := make([]interface{}, 0)
        data = append(data, m.Args)
        data = append(data, m.Kwargs)
        return json.Marshal(data)
    }
    

    Try it on the Playground