JSON marshal example

Here’s a simple example that demonstrates how to use the json.Marshal function in Go to encode a Go value into a JSON-encoded byte slice:

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

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

	b, err := json.Marshal(p)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}

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 byte slice is then cast to a string and printed to the console using the fmt.Println function.

If the encoding operation is successful, the output will be:

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

Comments

Leave a Reply

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