Golang : Unmarshal JSON from http response
For this tutorial, we will learn how to unmarshal JSON data retrieved from http.Get()
function. Using the HTTP response JSON data tutorial as example, the codes below will grab the JSON data and unmarshal them into struct.
NOTE : This example is also useful ... as a way for you to mock JSON reply to test your API.
The first part, will be the server generating the JSON data. Simple program with static JSON response :
jsonresponse.go
package main
import (
"net/http"
)
func Employees(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
jsonStr := `[{"Name":"Adam","Age":36,"Job":"CEO"},
{"Name":"Eve","Age":34,"Job":"CFO"},
{"Name":"Mike","Age":38,"Job":"COO"}]`
w.Write([]byte(jsonStr))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/employees", Employees)
http.ListenAndServe(":8080", mux)
}
build this program and run it at the background.
Point your browser to http://127.0.0.1:8080/employees
should give you this reply
[{"Name":"Adam","Age":36,"Job":"CEO"},
{"Name":"Eve","Age":34,"Job":"CFO"},
{"Name":"Mike","Age":38,"Job":"COO"}]
this part will be the client requesting the JSON data and convert it into a struct :
processjsonresponse.go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Employee struct {
Name string
Age int
Job string
}
func main() {
// url will return
// [
// {"Name":"Adam","Age":36,"Job":"CEO"},
// {"Name":"Eve","Age":34,"Job":"CFO"},
// {"Name":"Mike","Age":38,"Job":"COO"}
// ]
url := "http://127.0.0.1:8080/employees"
resp, err := http.Get(url)
defer resp.Body.Close()
if err != nil {
panic(err)
}
// read json http response
jsonDataFromHttp, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var jsonData []Employee
err = json.Unmarshal([]byte(jsonDataFromHttp), &jsonData) // here!
if err != nil {
panic(err)
}
// test struct data
fmt.Println(jsonData)
}
If everything goes well, executing processjsonresponse.go should give you this line :
[{Adam 36 CEO} {Eve 34 CFO} {Mike 38 COO}]
Useful link : http://jsonlint.com/ - to verify is the JSON result is valid or not.
Reference :
See also : Convert JSON to CSV in Golang
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.2k Golang : Another camera capture GUI application with GTK and OpenCV
+5.1k How to check with curl if my website or the asset is gzipped ?
+12.9k Generate salted password with OpenSSL example
+11.6k Golang : Save webcamera frames to video file
+10.2k Golang : Flip coin example
+21.7k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+8.7k Golang : Intercept and compare HTTP response code example
+11.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+7.4k Golang : Get today's weekday name and calculate target day distance example
+8.6k Golang : Inject/embed Javascript before sending out to browser example
+6.6k Golang : Takes a plural word and makes it singular
+9.5k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral