I'm learning Go and am trying to build a JSON request body of this shape the name
values are created dynamically based on a provided string. The JSON looks like this based on the input string "joan,john"
{
"reviewers": [
{"user": {"name": "joan"}},
{"user": {"name": "john"}}
]
}
I've searched how to build a slice of maps and have put together the code below but am getting complier errors. Where are am I going wrong?
type HTTPRequestBody struct {
Reviewers ReviewersArray `json:"reviewers,omitempty"`
}
type ReviewersArray struct {
Rs []struct {
Users User
}
}
type User struct {
User Name `json:"user`
}
type Name struct {
Name string `json:"name`
}
func addReviewers(reviewers string) *ReviewersArray {
reviewersSplit := strings.Split(reviewers, ",")
rArray := &ReviewersArray{}
for _, r := range reviewersSplit {
u := &User{User: Name{Name: r}}
// Error: cannot use u (variable of type *User) as struct{Users User} value in argument to append
rArray.Rs = append(rArray.Rs, u)
}
return rArray
}
func main() {
testReviewers := "joan,john"
prReviewers := addReviewers(testReviewers)
requestBody := &HTTPRequestBody{
// Error: cannot use prReviewers (variable of type *ReviewersArray) as ReviewersArray value in struct literal
Reviewers: prReviewers,
}
jsonData, _ := json.MarshalIndent(requestBody, "", " ")
fmt.Println(string(jsonData))
}
Top comments (2)
Try this
Thank you Stephen, I really appreciate it ๐