← All Articles

How to parse JSON in GO

Posted on

The go standard library has all you json needs covered. The JSON package has methods for both encoding and decoding to/from JSON.

package main
import "fmt"
import "log"
import "encoding/json"

type person struct {
	Name string
}

func main() {
	var p person
	b := []byte(`{"name": "Claus Witt"}`)
	err := json.Unmarshal(b, &p)
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Println(p.Name)
	}
}

First we import three packages fmt, for outputting the final result, log for logging errors and finally encoding/json for parsing the json string.

We use the same simple json string as the other examples. But this time there is a bit more ceremony. Even though you can parse arbitrary json strings into data structures you can use - the preferred way to decode a string is to define a struct into which the string will be decoded. So even though you need to write a bit more code, you’ll get compile time guarantees for your data.

We define a struct with a single string field. And the enter the json string as an array of raw bytes.

Finally we call json.Unmarshall for decoding the string into the struct - and printing the decoded name from the struct.

polyglotbitsgoparse-json