我正在尝试以{{"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和演示中所示。
或者,我如何probs := Problems{prob0, prob1, prob2, etc}
在不提前知道是否会添加或省略问题项目的情况下随意组合?
package main
import (
"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"}]
}
HUX布斯
慕仙森
相关分类