I'm trying to find an efficient way to convert flat data from a DB table into a nested JSON in Go.
This is my code to load my dataset into a slice of structs:
https://play.golang.org/p/_80nASVgds-
Which will produce the following json:
[{
"Globe": "World",
"Hemisphere": "Northern",
"Country": "USA"
}, {
"Globe": "World",
"Hemisphere": "Southern",
"Country": "Australia"
}, {
"Globe": "World",
"Hemisphere": "Southern",
"Country": "Brazil"
}, {
"Globe": "World",
"Hemisphere": "Southern",
"Country": "South Africa"
}, {
"Globe": "World",
"Hemisphere": "Northern",
"Country": "Spain"
}]
I'd like to be able to be able to encode the same dataset into something like:
type Globe struct {
Name string
Hemisphere []Hemisphere
}
type Hemisphere struct {
Name string
Country []Country
}
type Country struct {
Name string
}
So I could marshal Globe and get the same dataset in a nested form as such:
https://play.golang.org/p/r9OlCw_EwSA
{
"Name": "World",
"Hemisphere": [{
"Name": "Northern",
"Country": [{
"Name": "USA"
}, {
"Name": "Spain"
}]
}, {
"Name": "Southern",
"Country": [{
"Name": "Australia"
}, {
"Name": "South Africa"
}, {
"Name": "Brazil"
}]
}]
}
Is there any effective way of doing this other than looping through the dataset constantly and checking if a given property has already been added into the struct? My dataset is not ordered which makes it even more difficult to control the additions through loops.