How to unmarshal json in Go lang, when that json could be one-of-many different types

116 Views Asked by At

I am pulling some data out of a database with Go, and one of the fields of that structure is a JSON field that can be one of several types. How can I cast the parsed json to the correct type in Go?

type DBStruct struct {
  Type string `json:"type"`
  Config interface{} `json:"config"` //ConfigA or ConfigB
}

type ConfigA struct {
  Start string `json:"start"`
  End string  `json:"end"`
}

type ConfigB struct {
  Title string `json:"title"`
}

func doSomethingWithStruct(s DBStruct) {
  switch s.Type {
    case "ConfigA":
      config := GetConfigASomeHow(s.Config)
    case "ConfigB":
      config := GetConfigBSomeHow(s.Config)
  }
}
1

There are 1 best solutions below

0
Brandon Kauffman On

One option you could do is make fields optional and only have on type of config.

type DBStruct struct {
  Type string `json:"type"`
  Config interface{} `json:"config"` //ConfigA or ConfigB
}

type ConfigA struct {
  Title string `json:"title,omitempty"`
  Start string `json:"start,omitempty"`
  End string  `json:"end,omitempty"`
}

func doSomethingWithStruct(s DBStruct) {
  if s.Config.Title != "" {
     //Do conf with title
  }
}


There is probably a way to do this by building your own interface aswell, but I haven't used that before.