3 回答
TA貢獻1876條經驗 獲得超6個贊
一旦您將一個元素添加到您編組的數組/切片中,您就無能為力了。如果元素在數組/切片中,它將被編組(將包含在 JSON 輸出中)。該json.Marshal()函數如何猜測您不想編組的元素?它不能。
您必須排除不會出現在輸出中的元素。在您的情況下,您要排除空Problem結構。
最好/最簡單的是創建一個輔助函數,[]Problem為您創建切片,排除空結構:
func createProbs(ps ...Problem) []Problem {
// Remove empty Problem structs:
empty := Problem{}
for i := len(ps) - 1; i >= 0; i-- {
if ps[i] == empty {
ps = append(ps[:i], ps[i+1:]...)
}
}
return ps
}
使用它創建一個切片是這樣的:
probs := createProbs(prob0, prob1, prob2)
在Go Playground上嘗試修改后的應用程序。
修改后的代碼的輸出(注意缺少空結構):
[{"s":"s0","t":"t0"},{"s":"s1","t":"t1"},{"s":"s2","t":"t2"}]
[{"s":"s0","t":"t0"},{"s":"s2","t":"t2"}]
TA貢獻1827條經驗 獲得超8個贊
你不能輕易做到這一點??战Y構也是一個結構,它將被序列化為{}. 甚至nil值將被序列化為null.
以下代碼:包主
import (
"encoding/json"
"fmt"
)
func main() {
xs := []interface{}{struct{}{},nil}
b, _ := json.Marshal(xs)
fmt.Println(string(b))
}
將產生:
[{},null]
Playground
解決方案是為類型實現json.Marshaller接口Problems以跳過空結構。
- 3 回答
- 0 關注
- 297 瀏覽
添加回答
舉報
