JSON Decoding in Go (golang)

A quick example of JSON decoding (or unmarshaling) in Go. This is basically magic, it’s totally amazing I love it.

It’s possible to decode the JSON into generic maps, but if you know the structure you can get the JSON to populate native go structures automatically. You need to be mindful of types, go wont for example convert an int to a string, it’ll just ignore it.

This means if you have a JSON object that contains string:int key values and string:string key values and you try to populate a golang string map from it, you’ll lose all you string:int pairs. You are better off creating a struct to represent it as seen below.

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
package main
 
import (
  "encoding/json"
  "fmt"
)
 
type LogEntry struct {
  Time string
  Cpm   float32
  Duration  int32
  Accel_x_start int32
  Accel_y_start int32
  Accel_z_start int32
  Accel_x_end int32
  Accel_y_end int32
  Accel_z_end int32
}
 
type Log struct {
  Log_size      int
  Onyx_version  string
  UTC_offset    string
  Log_data      [] LogEntry
 
}
 
func main() {
 
  b := []byte(`{"log_size":61,"onyx_version":"pre11","UTC_offset":"undef","log_data":[{"time":"2012-10-23T22:23:54Z","cpm":46,"duration":30,"accel_x_start":-4,"accel_y_start":-97,"accel_z_start":-3,"accel_x_end":-1,"accel_y_end":-98,"accel_z_end":-2}]}`) 
 
  var l Log
  json.Unmarshal(b, &l)
 
  fmt.Printf("logsize: %d onyxversion: %s data1: %s\n",l.Log_size,l.Onyx_version,l.Log_data[0]);
}

Leave a Reply