DEV Community

loading...

Go - how to create a JSON body with an array (slice) of maps?

samatkins profile image Sam Atkins ・1 min read

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"}}
    ]
}
Enter fullscreen mode Exit fullscreen mode

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))
}
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

pic
Editor guide
Collapse
stephenafamo profile image
Stephen Afam-Osemene

Try this

type HTTPRequestBody struct {
    Reviewers []Reviewer `json:"reviewers,omitempty"`
}

type Reviewer struct {
    User User `json:"user"`
}

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

func addReviewers(reviewers string) []Reviewer {
    reviewersSplit := strings.Split(reviewers, ",")
    rArray := []Reviewer{}
    for _, r := range reviewersSplit {
        rArray = append(rArray, Reviewer{User: User{Name: r}})
    }
    return rArray
}
Enter fullscreen mode Exit fullscreen mode
Collapse
samatkins profile image
Sam Atkins Author

Thank you Stephen, I really appreciate it 😀