How to parse JSON in GO

Sat, Sep 10, 2016

Read in 1 minutes

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 {
	} else {

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.

See Also

How to parse JSON in Rust

Fri, Sep 16, 2016

Read more →

How to parse JSON in C++

Fri, Sep 16, 2016

Read more →

How to parse JSON in Elixir

Tue, Sep 6, 2016

Read more →

How to Read a file in Go

Thu, Nov 26, 2015

Read more →

How to Parse Json in Ruby

Thu, Sep 10, 2015

Read more →