The output that I want to get is in the format:
{"data": [ [ 0, [ "Brendan", "Fraser" ] ] , [ 1, [ "Keanu", "Reeves" ] ] ] }
To do this, I have defined the following struct:
type actors struct {
Data [][]interface{} `json:"data"`
}
The individual values Brendan , Fraser and Keanu, Reeves are coming from another data struct that is accessed in the format rec.records[0].value .
That is:
rec.records[0].value would correspond to Brendan
rec.records[1].value would correspond to Fraser and so on.
To assign values to this struct I am doing:
numberOfActCnt := 0
numberOfColParsed := 0
numberOfColumns := 3
var act actors
var res []actors
for i := 0; i < 2; i++ {
numberOfActCnt = numberOfActCnt + numberOfColParsed
for j := 0; j < 1; j++ {
act = actors{[][]interface{}{{i, []string{rec.records[numberOfActCnt].value, rec.records[numberOfActCnt+1].value}}}}
re, _ := json.Marshal(act)
fmt.Println(string(re))
numberOfColParsed = numberOfColumns - 1
}
}
This gives me the output:
{"data":[[0,["Brendan","Fraser"]]]}
{"data":[[1,["Keanu","Reeves"]]]}
How do I get the output in the format? :
{"data": [ [ 0, [ "Brendan", "Fraser" ] ] , [ 1, [ "Keanu", "Reeves" ] ] ] }
I think my struct is defined correctly, however how do I append values to the same json?
>Solution :
First, loop over all the records and store them inside the Data [][]any slice using append and then, after the loop, marshal the result.
numberOfActCnt := 0
numberOfColParsed := 0
numberOfColumns := 3
var res struct { Data [][]any `json:"data"` }
for i := 0; i < 2; i++ {
numberOfActCnt = numberOfActCnt + numberOfColParsed
for j := 0; j < 1; j++ {
res.Data = append(res.Data, []any{i, []string{rec.records[numberOfActCnt].value, rec.records[numberOfActCnt+1].value}})
numberOfColParsed = numberOfColumns - 1
}
}
re, err := json.Marshal(res)
if err != nil {
panic(err)
}
fmt.Println(string(re))
Note: any is an alias for interface{} since Go1.18, if you are on an older version of Go then you’ll need to keep using interface{}.