Hash934
Hash934

Reputation: 97

How to send a json array with different json objects in a http request

I want to send this data "id":"ab1" , "name":"Mash" in a http request in Go.

example : --data-urlencode 'data=[{"id":"ab1"},{"name":"Mash"}]'

How can I send this in golang . I have string values to send id and name as seperate json objects in an array like [{"id":"ab1"},{"name":"Mash"}]

Upvotes: 1

Views: 1882

Answers (1)

user14746222
user14746222

Reputation:

Use []interface{} to represent the data to be encoded to the JSON array. An interface{} can hold any Go value.

data := []interface{}{t1{ID: "123456"}, t2{Name: "Slash"}}
p, err := json.Marshal(data)
if err != nil {
    log.Fatal(err)
}

The types t1 and t2 in the snippet above are assumed to be the your types. Modify the names to your actual types.

Create a form:

form := url.Values{"data": []string{string(p)}}

Post the form:

http.DefaultClient.PostForm(url, form)

Upvotes: 2

Related Questions