I'm trying to generate JSON objects in the form of {{"s":"v1", "t":"v2"}, {"s":"v3", "t":"v4"}, etc}
via embedded structs in Go.
It all works out fine when all Problem
items in type Problems []Problem
are known ahead of time, as can be seen in func ONE()
below and in <kbd>Playground demo</kbd> here.
However, if some K:V pairs contain empty values I'd like to avoid getting {{a},{},{c}}
instead of the desired {{a},{c}}
, as in func TWO()
below and in demo.
Or alternatively, how can I compose probs := Problems{prob0, prob1, prob2, etc}
below arbitrarily without knowing ahead of time whether a prob item will be added or omitted?
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"}]
}