Array of a pointer in Go JSON marshalling


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

package main
import (

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)

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

         b1, _ := json.Marshal(MyJSON)


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 ?


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

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.

Answered By – mkopriva

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.