title: Convert flat data to nested JSON with Go
body: <p>I'm trying to find an efficient way to convert flat data from a DB table into a nested JSON in Go.<br/></p>
  
  <p>This is my code to load my dataset into a slice of structs:</p>
  
  <p><a href="https://play.golang.org/p/_80nASVgds-" rel="nofollow noreferrer">https://play.golang.org/p/_80nASVgds-</a></p>
  
  <p>Which will produce the following json:</p>
  
  <pre><code>[{
      "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"
  }]
  </code></pre>
  
  <p>I'd like to be able to be able to encode the same dataset into something like: <br/><br/></p>
  
  <pre><code>type Globe struct {
      Name       string
      Hemisphere []Hemisphere
  }
  
  type Hemisphere struct {
      Name    string
      Country []Country
  }
  
  type Country struct {
      Name string
  }
  </code></pre>
  
  <p>So I could marshal Globe and get the same dataset in a nested form as such:<br/></p>
  
  <p><a href="https://play.golang.org/p/r9OlCw_EwSA" rel="nofollow noreferrer">https://play.golang.org/p/r9OlCw_EwSA</a></p>
  
  <pre><code>{
      "Name": "World",
      "Hemisphere": [{
          "Name": "Northern",
          "Country": [{
              "Name": "USA"
          }, {
              "Name": "Spain"
          }]
      }, {
          "Name": "Southern",
          "Country": [{
              "Name": "Australia"
          }, {
              "Name": "South Africa"
          }, {
              "Name": "Brazil"
          }]
      }]
  }
  </code></pre>
  
  <p>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.</p>