展平一个结构并将其转换为map [string] string [关闭]

I have various different nested struct, for example:

type MyInnerType struct {
    hello int
}

type MyType struct {
    foo   string
    bar   MyInnerType
}

with a declaration like this, for example:

x = &MyType{
    foo: "hi"
    bar: MyInnerType{hello: 1}
}

I would like to convert it into flattened map of map[string]string like this:

{"foo":"hi", "hello":"1"}

I imagine this has to be done recursively, but also converting various values into string is an issue. I've found this library to help with it, but have not found any solution.

Is there any library that does this? If not, what can I do for myself to solve this?

There are a number of ways you can convert those types (or similarly shaped types) into your desired JSON.

The easiest would be to redefine your structs as below, then the default JSON marshaler will do what you want:

type MyInnerType int

type MyType struct {
  Foo string      `json:"foo"`
  Bar MyInnerType `json:"hello"`
}

If you really want to keep the structs you defined then you can implement a custom JSON marshaler via a MarshalJSON(...) method like so:

type MyInnerType struct {
  hello int
}

func (mit MyInnerType) MarshalJSON() ([]byte, error) {
  return []byte(strconv.Itoa(mit.hello)), nil
}

type MyType struct {
  Foo string      `json:"foo"`
  Bar MyInnerType `json:"hello"`
}

func main() {
  x := &MyType{
    Foo: "hi",
    Bar: MyInnerType{hello: 1},
  }
  bs, err := json.Marshal(x)
  if err != nil {
    panic(err)
  }
  fmt.Println(string(bs))
  // {"foo":"hi","hello":1}
}