Standard library / encoding/json

encoding/json.Marshaler

Custom JSON encoding interface. Marshal calls MarshalJSON on applicable values except nil pointers. Returned bytes must represent valid JSON. Expected stdout: '"GO"\n'.

Formal Syntax & Structure

go syntaxgo
type Marshaler interface {  MarshalJSON() ([]byte, error)}

Working Example

Example Snippetgo
package main
import (  "encoding/json"  "fmt"  "strings")
func must(e error) {  if e != nil {    panic(e)  }}
type Label string
func (l Label) MarshalJSON() ([]byte, error) { return json.Marshal(strings.ToUpper(string(l))) }func main() {  var m json.Marshaler = Label("go")  b, e := json.Marshal(m)  must(e)  fmt.Println(string(b))}
Go Reference