Standard library / encoding/json

encoding/json.Marshal()

Encode supported Go values as JSON. Exported struct fields are encoded; unsupported types, non-finite floats and cycles can fail. Check the returned error. Expected stdout: '{"name":"Ada"}\n'.

Formal Syntax & Structure

go syntaxgo
func Marshal(v any) ([]byte, error)

Parameters & Attributes

NameTypeDescription
vanyGo value to encode or destination pointer to decode, depending on the operation.

Return Value

([]byte, error)

Encoded bytes and an error (nil on success).

Working Example

Example Snippetgo
package main
import (  "encoding/json"  "fmt")
func must(e error) {  if e != nil {    panic(e)  }}
func main() {  b, e := json.Marshal(struct {    Name string `json:"name"`  }{"Ada"})  must(e)  fmt.Println(string(b))}
Go Reference