How To Parse Json Data in Golang

parse-json-golang

This tutorial help to understand How to send and receive json data in golang. The JSON is very popular cross platform data format.

This tutorial help to create and send json data to the golang application.

The main purpose of json format data is that can be consume any programming language.Its a easy to use and readable.There a lot of APIs are providing support of json data format. They can accept data in json format and send response to the client as a json format.

This tutorial will cover following topics –

  • How to receive Post JSON payload in golang.
  • Convert HTTP response into JSON and send to Client.

How To Access POST JSON Payload in Golang

The json data can be post as payloads to the server side, I am using golang as server side application, I will get json paylods and process data in json format.You can send and receive json data by "encoding/json" package, This package is use handle json data into golang.

func AddEmployee(w http.ResponseWriter, r *http.Request) {
type NewEmp struct {
    Name string `json:"Name"`
    Salary  string `json:"Salary"`
    Age  string `json:"Age"`
}

var emp NewEmp
decoder := json.NewDecoder(r.Body).Decode(&emp)
fmt.Printf("%+v\n", emp)
}

In the above code, I have created a NewEmp struct and mapped to json payloads data against the json key, then created emp variable of NewEmp struct type.

Then, we have decoded posted body data and mapped with emp variable.We have print struct mapped data into console using fmt.Printf() method.

Convert Response Data in Json format in Golang

This is vise-versa of above functionality, Like we have received json data and converted into struct to process in golang. This steps is used to receive json data as response and mapped with struct.We need to decode json data and send json as a response, we will convert response body data into json data and send to client.

func AddUser(w http.ResponseWriter, r *http.Request) {
type NewEmp struct {
    Name string `json:"Name"`
    Salary  string `json:"Salary"`
    Age  string `json:"Age"`
}
defer resp.Body.Close()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
var data NewEmp
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
    fmt.Println(err)
}

res, err := json.Marshal(&data)
w.Write(res)
}

We are fetching a single employee details from the third party. We will get response in json format and use Decode() method.It buffers the entire JSON value in memory before unmarshalling it into a Go value, We will use json.marshal() method to convert Go object into JSON.

How to access path Variable in Go

The variable is very useful to send a limited number of variables using URI to the server, like 'api/v1/test/id/1', where id is the path variable and value is 1, You can define path variables without a key name as well, like 'api/v1/test/1'. You can access path variable into handler method using MUX package as like below:

vars := mux.Vars(r)
fmt.Println("The id is: ", vars["id"])