Composing arbitrary JSON objects in embedded structs in Go -


i'm trying generate json objects in form of {{"s":"v1", "t":"v2"}, {"s":"v3", "t":"v4"}, etc} via embedded structs in go.

it works out fine when problem items in type problems []problem known ahead of time, can seen in func one() below , in playground demo here.

however, if k:v pairs contain empty values i'd avoid getting {{a},{},{c}} instead of desired {{a},{c}}, in func two() below , in demo.

or alternatively, how can compose probs := problems{prob0, prob1, prob2, etc} below arbitrarily without knowing ahead of time whether prob item 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 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"}] } 

once add element array/slice marshal, there's nothing can it. if element in array/slice, marshalled (will included in json output). how json.marshal() function guess elements don't want marshal? can't.

you have exclude elements don't appear in output. in case want exclude empty problem structs.

best/easiest create helper function creates []problem slice you, empty structs excluded:

func createprobs(ps ...problem) []problem {     // remove empty problem structs:     empty := problem{}     := len(ps) - 1; >= 0; i-- {         if ps[i] == empty {             ps = append(ps[:i], ps[i+1:]...)         }     }     return ps } 

using creating slice this:

probs := createprobs(prob0, prob1, prob2) 

try modified application on go playground.

output of modified code (notice empty struct missing):

[{"s":"s0","t":"t0"},{"s":"s1","t":"t1"},{"s":"s2","t":"t2"}] [{"s":"s0","t":"t0"},{"s":"s2","t":"t2"}] 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -