在go中创建异构json数组

假设我在使用这样的结构:</ p>

  类型Message struct {
Args [] interface {}
Kwargs map [string] interface {}
}

message:= Message {
[] interface {} {1、2、3、4},

map [string] interface {} {“ a”:2,“ b”:3},
}
</ code> </ pre>

我应该如何整理邮件中的内容 这样的JSON?</ p>

  [[1,2,3,4],{“ a”:2,2,“ b”:3}] 
</ code> </ pre>
</ div>

展开原文

原文

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}]

douji1077
douji1077 编组此值:[]interface{}{message.Args,message.Kwargs}对您来说足够好了吗?
接近 2 年之前 回复

2个回答



您可以在您的结构中添加编组方法来处理逻辑。 </ p>

  func(m消息)MarshalJSON()([] byte,error){
data:= make([] interface {},0)

data = append(data,m.Args)
data = append(data,m.Kwargs)
返回json.Marshal(data)
}
</ code> </ pre>

在操场上尝试 </ p>
</ div >

展开原文

原文

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

What you want in your output is a JSON array holding the Args and Kwargs fields of your message struct value, so you may get what you want by marshaling the following slice value:

[]interface{}{message.Args, message.Kwargs}

For example:

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

err := json.NewEncoder(os.Stdout).
    Encode([]interface{}{message.Args, message.Kwargs})

fmt.Println(err)

Output of the above (try it on the Go Playground):

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

This works for this specific case. If you want a general solution which marshals fields of a struct value like elements of an array, you may create a helper function that "packs" fields into a slice:

func getFields(i interface{}) (res []interface{}) {
    v := reflect.ValueOf(i)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
        return nil
    }

    for i := 0; i < v.NumField(); i++ {
        f := v.Field(i)
        if f.CanInterface() {
            res = append(res, f.Interface())
        }
    }
    return res
}

The above getFields() accepts struct values and pointers to structs. Example using it:

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

err := json.NewEncoder(os.Stdout).Encode(getFields(message))
fmt.Println(err)

err = json.NewEncoder(os.Stdout).Encode(getFields(&message))
fmt.Println(err)

Output (try it on the Go Playground):

[[1,2,3,4],{"a":2,"b":3}]
<nil>
[[1,2,3,4],{"a":2,"b":3}]
<nil>
dongtiaozhou4914
dongtiaozhou4914 非常感谢您的时间和答复。 我终于发现使用json接口(MarshalJson和UnmarshalJson)要容易一些。
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐