Home > Software design >  Array of a pointer in Go JSON marshalling
Array of a pointer in Go JSON marshalling

Time:03-21

I've the following code, where I want to just test whether I'm marshaling my JSON correctly or not:

package main
import (
    "encoding/json"
    "fmt"
)

 
type TestFile struct {

        Download_Seconds        int                `json:"download_seconds"`                                                                             
        Name                    string             `json:"name"`                                                            
}

 
type TestFileList struct {

        File                    *TestFile          `json:"file"`                                                                                                                                                           
}


type TestSpec struct {

        Files                   []*TestFileList    `json:"files"`                                                                                                 

}

 

func main() {
         r := new(TestSpec)
         b, _ := json.Marshal(r)
         fmt.Println(string(b))

         MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}}

         b1, _ := json.Marshal(MyJSON)
         fmt.Println(string(b1))

} 

I'm getting this error:

.\go_json_eg2.go:28:32: syntax error: unexpected &, expecting type.

Line no: 28 for my code is MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}}

Fairly new to Go marshaling. I figured I'm doing this wrong []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}.

How to fix this ?

CodePudding user response:

&TestSpec{
    Files: []*TestFileList{
        {File: &TestFile{Download_Seconds: 600, Name: "filename1"}},
        {File: &TestFile{Download_Seconds: 1200, Name: "filename2"}},
    },
}

https://go.dev/play/p/I30Mm0CxrUT

Notice that besides the error pointed out by Zombo in the comments, you also left out the curly braces that delimit the individual elements in the slice, i.e. you have {File: ..., File: ...}, but it should be {{File: ...}, {File: ...}}.

You can read more about Composite Literals here.

  • Related