-1

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)
  }
}
Kevin Whitaker
  • 12,435
  • 12
  • 51
  • 89
  • If you are asking about _unmarshal_, and are unmarshaling into `any`, then the only choice is to copy the values into the desired structure. – JimB May 01 '23 at 17:44
  • Does [How to unmarshal JSON into interface{} in Go?](https://stackoverflow.com/a/28254703/5728991) answer the question? – Charlie Tumahai May 01 '23 at 17:50
  • Or are you looking for someting like this: [How to accommodate for 2 different types of the same field when parsing JSON](https://stackoverflow.com/questions/72095328/how-to-accommodate-for-2-different-types-of-the-same-field-when-parsing-json)? – JimB May 01 '23 at 17:54

1 Answers1

0

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.

Brandon Kauffman
  • 1,515
  • 1
  • 7
  • 33