亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Go 中的嵌入式結構中組合任意 JSON 對象

在 Go 中的嵌入式結構中組合任意 JSON 對象

Go
蠱毒傳說 2021-09-27 16:05:46
我正在嘗試以{{"s":"v1", "t":"v2"}, {"s":"v3", "t":"v4"}, etc}Go 中的嵌入式結構的形式生成 JSON 對象。當提前知道所有Problem項目時,一切都很好type Problems []Problem,如ONE()下面的func和Playground demo此處所示。但是,如果某些 K:V 對包含空值,我想避免獲取{{a},{},{c}}而不是所需的{{a},{c}},如TWO()下面的func和演示中所示?;蛘撸胰绾蝡robs := Problems{prob0, prob1, prob2, etc}在不提前知道是否會添加或省略問題項目的情況下隨意組合?package mainimport (    "encoding/json"    "fmt")type Problem struct {     S string `json:"s,omitempty"`     T string `json:"t,omitempty"`} type Problems []Problem func main() {     ONE()     TWO()} func ONE() {     prob0 := Problem{S: "s0", T: "t0"}     prob1 := Problem{S: "s1", T: "t1"}     prob2 := Problem{S: "s2", T: "t2"}     probs := Problems{prob0, prob1, probe}       // fmt.Println(probs) // CORRECT: [{s0 t0} {s1 t1} {s2 t2}]     b, _ := json.Marshal(probs)     fmt.Println(string(b))       // CORRECT: [{"s":"s0","t":"t0"},{"s":"s1","t":"t1"},{"s":"s2","t":"t2"}]``} func TWO() {     prob0 := Problem{S: "s0", T: "t0"}     prob1 := Problem{S: "", T: ""} // empty values omited BUT NOT {}     prob2 := Problem{S: "s2", T: "t2"}     probs := Problems{prob0, prob1, probe}       // fmt.Println(probs)       // GOT:    [{s0 t0} { } {s2 t2}]       // WANTED: [{s0 t0} {s2 t2}]     b, _ := json.Marshal(probs)     fmt.Println(string(b))       // GOT:    [{"s":"s0","t":"t0"},{},{"s":"s2","t":"t2"}]       // WANTED: [{"s":"s0","t":"t0"},{"s":"s2","t":"t2"}]}
查看完整描述

3 回答

?
HUX布斯

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


查看完整回答
反對 回復 2021-09-27
?
慕仙森

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以跳過空結構。


查看完整回答
反對 回復 2021-09-27
  • 3 回答
  • 0 關注
  • 297 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號