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

1
2
3
4
5
{
"gold": 1271,
"silver": 1284,
"platinum": 1270
}

Then parse the JSON object like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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()
}