Home How to get array from json post request and append it to slice []string in golang
Reply: 1

How to get array from json post request and append it to slice []string in golang

Mohamad Fadil
1#
Mohamad Fadil Published in 2018-02-13 16:56:01Z

I have a api endpoint that requires the user to post array of ids into it. So my problem is how do i fetch these array in body of the request and then iterate and pass every id inside the posted array to a slice of string.

this is the current way i am doing it and i can seem to get the array

body, err := ioutil.ReadAll(r.Body)
if err != nil {
    fmt.Printf("%#v", err)
}

fmt.Printf("%#v", body)

So how do i get the array in the body of the req and pass it to the string slice. Thanks in advance!

Julian Espinel
2#
Julian Espinel Reply to 2018-02-13 17:22:34Z

Assuming your body follows this structure:

{
    "ids": [1, 2, 3]
}

You can put the "ids" array into a slice like this:

package main

import "fmt"
import "encoding/json"

type Request struct {
    Ids []int `json:"ids"`
}

func main() {
    body_str := `{ "ids": [1, 2, 3] }`
    var request Request
    err := json.Unmarshal([]byte(body_str), &request)
    if err != nil {
        fmt.Print(err)
    }
    fmt.Printf("%#v", request.Ids)
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.343813 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO