合并两个不同的结构

Merge two different structs

我有两个名为“发票”、“交易”的结构。这些是 GORM 模型。我想合并这些结构并转换 json.

示例:

type Invoice struct {
     gorm.Model
     DocType string `json:"docType"`
     Total float64 `json:"total"`
}

type Transaction struct {
     gorm.Model
     DocType string `json:"docType"`
     Total float64 `json:"total"`
     Account uint `json:"account"`
}

我想要这样的回复;

[
{docType:"invoice", total: "123.00"}
{docType:"transaction", account:"1", total: "124.00"}
{docType:"invoice", total: "125.00"}
]

如果您想要在问题中列出的回复,您可以使用通用数组 []interface{} 并将其转换为 JSON。

inv1 := Invoice{
    DocType: "invoice",
    Total:   123.00,
}
inv2 := Invoice{
    DocType: "invoice",
    Total:   125.00,
}
tran := Transaction{
    DocType: "transaction",
    Total:   124.00,
    Account: 1,
}
bytes, _ := json.Marshal([]interface{}{inv1, tran, inv2})
fmt.Println(string(bytes))

无论你是用 gorm 的值填充结构,还是像我在这里做的那样自己初始化它们都没有关系。


阅读评论,您似乎有两个结构切片,您想将两个切片合并为一个切片,然后编码为 JSON。

你可以这样做:

arr1 := []Invoice{inv1, inv2}
arr2 := []Transaction{tran}

combined := make([]interface{}, 0, len(arr1)+len(arr2))
for i := range arr1 {
    combined = append(combined, arr1[i])
}
for i := range arr2 {
    combined = append(combined, arr2[i])
}
bytes, _ := json.Marshal(combined)
fmt.Println(string(bytes))

在这里,我只是使用我自己创建的切片,但这些很可能来自 gorm 的 db.Find(&arr1)