2

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.

Jose Bagatelli
  • 1,367
  • 1
  • 15
  • 32
  • It looks like you're after a group-by type operation. This link is python, but I think it explains the approach http://jakevdp.github.io/blog/2017/03/22/group-by-from-scratch/ You might also find some insight here (not quite a duplicate question, yours is more general) https://stackoverflow.com/questions/39987023/golang-group-and-sum-slice-of-structs – munk Mar 11 '19 at 16:05
  • Hi, using the `encoding/json` library you will be able to accomplish that. If you implement a `json.Unmarshaler` interface you are able to produce whatever result in `[]byte`. https://golang.org/pkg/encoding/json/#Unmarshaler – Jota Santos Mar 11 '19 at 16:58
  • @JamiloSantos. I’m not asking how to simply unmarshal a json to a struct. – Jose Bagatelli Mar 11 '19 at 23:15
  • https://blog.gopheracademy.com/advent-2016/advanced-encoding-decoding/ – Oshan Wisumperuma May 08 '19 at 16:33

0 Answers0