Home > Software design >  Populate a struct with an array of sub-structs to turn into json
Populate a struct with an array of sub-structs to turn into json

Time:10-08

I’m trying to post some JSON. Using the JSON-to-Go tool I have this struct defined:

type IssueSetState struct {
    ID           string `json:"id"`
    CustomFields []struct {
        Value struct {
            Name string `json:"name"`
        } `json:"value"`
        Name string `json:"name"`
        Type string `json:"$type"`
    } `json:"customFields"`
}

I’m trying to populate it with some data that I can then pass into the http library:

    jsonValues := &IssueSetState{
        ID: resultEntityId.ID,
        CustomFields: []{
            Value: {
                Name: "Fixed",
            },
            Name: "State",
            Type: "StateIssueCustomField",
        },
    }
    jsonEncoded := new(bytes.Buffer)
    json.NewEncoder(jsonEncoded).Encode(jsonValues)

I keep getting errors like:

./main.go:245:19: syntax error: unexpected {, expecting type
./main.go:246:9: syntax error: unexpected :, expecting comma or }
./main.go:249:8: syntax error: unexpected : at end of statement
./main.go:251:4: syntax error: unexpected comma after top level declaration

I’m sure the mistake I’m making is a simple one, but I’m new to Go.

CodePudding user response:

One possible way is to define named structs for every anonymous struct you have.

type IssueSetState struct {
    ID           string        `json:"id"`
    CustomFields []CustomField `json:"customFields"`
}

type CustomField struct {
    Value Value  `json:"value"`
    Name  string `json:"name"`
    Type  string `json:"type"`
}

type Value struct {
    Name string `json:"name"`
}

Now you can create it like this:

IssueSetState{
    ID: resultEntityId.ID,
    CustomFields: []CustomField{
        {
            Value: Value{
                Name: "Fixed",
            },
            Name: "State",
            Type: "StateIssueCustomField",
        },
        {
            Value: Value{
                Name: "Fixed",
            },
            Name: "State",
            Type: "StateIssueCustomField",
        },
    },
}

CodePudding user response:

So you're initializing the jsonValue badly.

You can fix it in 2 ways:

  1. https://play.golang.org/p/LFO4tOLyG60

    making structures flat

  2. https://play.golang.org/p/TyFfaMf7XeF

    by repeating the structure definition when declaring value

The first one should be easier and clearer.

  •  Tags:  
  • go
  • Related