Learn how to parse JSON objects with golang.
JavaScript Object Notation (JSON) is a data exchange format. While originally designed for JavaScript, these days many computer programs interact with the web and use JSON.
Interacting with the web is mostly done through APIs (Application Programmable Interface), in JSON format.
golang JSON example
Parse JSON
You can parse a JSON object with golang. The object will then be converted to a golang object.
Start by creating a json object
{
"gold": 1271,
"silver": 1284,
"platinum": 1270
}
Then parse the JSON object like this:
package main
import (
"encoding/json"
"fmt"
)
func main() {
// define data structure
type DayPrice struct {
Gold int
Silver int
Platinum int
}
// json data
data := `{"gold": 1271,"silver": 1284,"platinum": 1270}`
var obj DayPrice
// unmarshall it
err := json.Unmarshal([]byte(data), &obj)
if err != nil {
fmt.Println("error:", err)
}
// can access using struct now
fmt.Printf("Gold : $ %d\n", obj.Gold);
fmt.Printf("Silver : $ %d\n", obj.Silver);
fmt.Printf("Platinum : $ %d\n", obj.Platinum);
}
Parse JSON from URL
You can get JSON objects directly from the web and convert them to golang objects. This is done through an API endpoint
package main
import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
// Define data structure
type Response struct {
TradeID int
Price string
Size string
Bid string
Ask string
Volume string
Time string
}
func get_content() {
// json data
url := "https://api.gdax.com/products/BTC-EUR/ticker"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data Response
// unmarshall
json.Unmarshal(body, &data)
//fmt.Printf("Results: %v\n", data)
// print values of the object
fmt.Printf("Price: $ %s\n", data.Price)
fmt.Printf("Price: $ %s\n", data.Bid)
fmt.Printf("Price: $ %s\n", data.Ask)
os.Exit(0)
}
func main() {
get_content()
}