I
I
impressive172020-04-25 20:01:08
go
impressive17, 2020-04-25 20:01:08

How to parse JSON in golang?

How to parse a post request in a handler and get the value on GO from there?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-04-25
@EvgenyMamonov

Example

// AddUserRequest структура с параметрами запроса.
type AddUserRequest struct {
    Name string `json:"name"`
    Login string `json:"login"`
    Password string `json:"password"`
}

func AddUserHandlerFunc(w http.ResponseWriter, r *http.Request) {
        var req AddUserRequest
        err := json.NewDecoder(r.Body).Decode(&req);
        if err != nil {
        /// ....
        }
        // тут у вас будет заполненная структура req 
}

JSON request should be like this
{
    "name": "Иван",
    "login": "Ivan",
    "password": "123"
}

If the JSON structure is not known in advance, you can use this library
https://github.com/valyala/fastjson

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question