This is an automated archive.
The original was posted on /r/golang by /u/Mighmi on 2023-08-08 21:13:44+00:00.
The relevant service makes API calls, collecting ugly nested JSON of different known formats (the format is according to the object described, e.g. boats, cars, houses) and saves them in a more consistent manner with only the relevant data. I want to use the structs, not an ugly any any map.
Now, I know precisely why the compiler can’t allow:
func ReformatJSON(body io.Reader, structType string) io.Reader {
var seriesdatamap structType // the query builder would return this e.g. “house”
err := json.NewDecoder(body).Decode(&seriesdatamap)
check(err)
}
But due to the amount of formats, ~1000 loc of interface and method definitions seems excessive and difficult to manage. My first instinct is something ugly and hacky like:
- Make package only Marshaller and Unmarshaller interface{} so everything automatically satisfies them but it doesn’t spill over elsewhere.
- Removing this ReformatJSON func, and instead copying the logic in every case of an 80 long switch statement, with a case for each type.
case “HOUSE”:
url = baseUrl + “&itemtype=house” + “querry” + apiKey
var seriesdatamap House
err := json.NewDecoder(body).Decode(&seriesdatamap)
But what’s the best way to deal with this? Any example package doing something similar?