Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding elements to JSON dynamically from a Go struct

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 .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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{}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading