Go by Example: JSON

Go provides built-in support for encoding and decoding JSON data. JSON (JavaScript Object Notation) is a widely-used data interchange format that is human-readable and easy to generate and parse.

Here’s a basic example that demonstrates how to encode a Go value into JSON and then decode it back into a Go value:

package main

import (

type Person struct {
	Name string
	Age  int

func main() {
	p := Person{Name: "John Doe", Age: 30}

	// Encode p into JSON
	b, err := json.Marshal(p)
	if err != nil {

	// Decode JSON into p2
	var p2 Person
	err = json.Unmarshal(b, &p2)
	if err != nil {

In this example, a type Person is defined with two fields, Name and Age. A value of type Person is created and stored in the p variable.

The json.Marshal function is called to encode p into a JSON-encoded byte slice, which is stored in the b variable. The json.Unmarshal function is then called to decode b into a value of type Person, which is stored in the p2 variable.

If the encoding and decoding operations are successful, the output will be:

{"Name":"John Doe","Age":30}
{John Doe 30}

Note that in this example, the Go value is being encoded into a byte slice and then decoded back into a Go value. However, JSON encoding and decoding can also be performed directly with io primitives, such as os.File, bytes.Buffer, and net.Conn, for example. The encoding/json package provides a rich set of options and functions for working with JSON data in Go.


Leave a Reply

Your email address will not be published. Required fields are marked *