converting slice of items into nested array

310 views
Skip to first unread message

aa...@pop42.com

unread,
Dec 7, 2016, 1:02:58 PM12/7/16
to golang-nuts
I'm pretty new to golang and struggling a bit with converting flat database results into a nested JSON object.  

As an example... I have 

type item struct {
raceID   string
racename string
name     string
votes    int32
}

type race struct {
raceID   string
racename string
racers
}

type racers []racer

type racer struct {
name  string
votes int32
}

[]item is what I get back from my db query and I want to convert it into a json object that matches the race struct.

basically I want to convert 
items := []item{
item{"1", "racename1", "scooby", 1000},
item{"1", "racename1", "scrappy", 9000},
item{"1", "racename1", "shaggy", 1000},
item{"2", "racename2", "shaggy", 450},
item{"2", "racename2", "fred", 550},
}

into something like

[{
"raceID": "1",
"racename": "racename1",
"racers": [{
"name": "scooby",
"votes": 1000
}, {
"name": "scrappy",
"votes": 9000
}, {
"name": "shaggy",
"votes": 1000
}]
}, {
"raceID": "2",
"racename": "racename2",
"racers": [{
"name": "shaggy",
"votes": 450
}, {
"name": "fred",
"votes": 550
}]
}]

I'm pretty sure I need to use maps and append some slices... but any pointing in the right direction would surely be appreciated.


Mikael Gustavsson

unread,
Dec 8, 2016, 3:55:27 AM12/8/16
to golang-nuts
There's no need to use maps, you want to follow this pattern:

for i := range items {
  if i==0 || !grouped(i-1, i) {
    appendToResult
  }
  appendToGroup
}

Here's the full example: https://play.golang.org/p/1e0rDDmq7b

Marvin Renich

unread,
Dec 8, 2016, 8:22:25 AM12/8/16
to golang-nuts
* Mikael Gustavsson <slv...@gmail.com> [161208 03:55]:
Note that this only works if the input slice is sorted, which it is in
the example data given by the OP, but that constraint was not explicitly
stated. If the input is not sorted, you must either sort it first, use
a map, or perform a search in each iteration.

If the input data is not guaranteed to be sorted, minimal changes to the
above would work: https://play.golang.org/p/4GsVUV_fBs

The map is only used to perform the search efficiently, and is no longer
used after the for loop.

...Marvin

Tamás Gulácsi

unread,
Dec 8, 2016, 9:31:24 AM12/8/16
to golang-nuts
Use capitalized field names and struct tags - lowercase is not exported, encoding/json does not see it.
Reply all
Reply to author
Forward
0 new messages