How to create a JSON body with an array (slice) of maps?

I’m learning Go and am building a simple CLI which makes HTTP requests. I’m 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)

        // rArray = append(rArray, u)
        // rArray{Rs: append(rArray.Rs, u)},
        // rArray{Rs: append(rArray, 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))
}

https://play.golang.org/p/dFv9KA3Gjr_D

1 Like

Thanks Charles, really appreciate your response :slight_smile:

Here it is using structs instead of map[string]interface{} if that’s easier: https://play.golang.org/p/UCt7t3xY8oK

1 Like