-3

I have two structs struct:

type A struct {
    Zip string `json:"zip"`
}

type B struct {
    Foo string `bson:"foo"`
    Bar A      `json:"bar"`
}

When I try to json.Marshal the B type, the Bar field does not get converted correctly. The fields are OK, but the values are always empty. The output looks like this:

{"foo": "some-string-value", "bar": {"zip": ""}}

What am I doing wrong?

Daniel Ribeiro
  • 10,156
  • 12
  • 47
  • 79

1 Answers1

4

Your Zip field in A is not populated.

type A struct {
    Zip string `json:"zip"`
}

type B struct {
    Foo string `bson:"foo"`
    Bar A      `json:"bar"`
} 
func main() {
    one := A{"35000"}
    two := B{"Foo", one}
    json, _ := json.Marshal(two)
    fmt.Printf("%s\n", json)
}

Output is (https://play.golang.org/p/kyG1YabpSe):

{"Foo":"Foo","bar":{"zip":"35000"}}

Even with a map

type A struct {
   Zip string `json:"zip"`
}
type B struct {
   Foo string `bson:"foo"`
   Bar A      `json:"bar"`
}
func main() {
   m := make(map[string]B)

   for x := 0; x < 10; x++ {
      m[strconv.Itoa(x)] = B{"Hello", A{"35000"}}
   }

   json, _ := json.Marshal(m)
   fmt.Printf("%s\n", json)
}

https://play.golang.org/p/qCsmAGzo4H

Output is good, i don't understand where you are wrong.

Boris Le Méec
  • 2,383
  • 1
  • 16
  • 31
  • I have a map of `B` items, and when I try to `json.Marshal(myMap)`, the `Bar` field is populated with empty string values. – Daniel Ribeiro Nov 17 '16 at 08:52
  • @DanielRibeiro Can you update your question with the exact code the problem is observed in ? There is no mention of `myMap` or map of `B` items in the question. – John S Perayil Nov 17 '16 at 09:57