json

package module
v0.0.0-...-79a48bf Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2025 License: MIT Imports: 12 Imported by: 15

README

go-json

Package json implements JSON encoders and decoders, for the Go programming language.

Package json is meant to be a replacement for the Go built-in "encoding/json" package.

Package json also includes a number of addtional useful features (that the Go built-in "encoding/json" package does not have).

Documention

Online documentation, which includes examples, can be found at: http://godoc.org/github.com/reiver/go-json

GoDoc

Examples

To marshal a Go value to JSON, you can do something similar to the following:

import "github.com/reiver/go-json"

// ...

jsonBytes, err := json.Marshal(value)

Installation

To install package json do the following:

GOPROXY=direct go get https://github.com/reiver/go-json

Author

Package json was written by Charles Iliya Krempeaux

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BareModifierFunc

func BareModifierFunc(bytes []byte) ([]byte, error)

BareModifierFunc is the modifier that, in the DefaultUsher, is the implementation behind the "bare" modifier.

For example:

struct {

	// ...

	Banana string `json:"banana,bare"`

	// ...

}

func Compact

func Compact(dst io.Writer, src []byte) error

func ErrEmpty

func ErrEmpty(message string) error

ErrEmpty returns an error of type ErrorEmpty.

ErrorEmpty is used with the "omitempty" struct-field tag option.

func Marshal

func Marshal(value any) ([]byte, error)

Marshal returns the JSON version of 'value'.

For example:

bytes, err := json.Marshal(value)

See Usher.Marshal for more information.

Calling:

bytes, err := json.Marshal(value)

Is the same as calling:

bytes, err := json.DefaultUsher.Marshal(value)

json.Marshal() is a convenience function for json.DefaultUsher.Marshal().

func MarshalBool

func MarshalBool(value bool) []byte

MarshalBool returns the JSON version of a Go bool.

func MarshalInt

func MarshalInt(value int) []byte

MarshalInt returns the JSON version of a Go int.

func MarshalInt16

func MarshalInt16(value int16) []byte

MarshalInt16 returns the JSON version of a Go int16.

func MarshalInt32

func MarshalInt32(value int32) []byte

MarshalInt32 returns the JSON version of a Go int32.

func MarshalInt64

func MarshalInt64(value int64) []byte

MarshalInt64 returns the JSON version of a Go uint64.

func MarshalInt8

func MarshalInt8(value int8) []byte

MarshalInt8 returns the JSON version of a Go int8.

func MarshalSlice

func MarshalSlice[T any](value []T) ([]byte, error)

MarshalString returns the JSON version of a Go string.

func MarshalString

func MarshalString(value string) []byte

MarshalString returns the JSON version of a Go string.

func MarshalTextMarshaler

func MarshalTextMarshaler(textMarshaler encoding.TextMarshaler) ([]byte, error)

MarshalTextMarshaler returns the JSON version of the successful result from encoding.TextMarshaler..

func MarshalUint

func MarshalUint(value uint) []byte

MarshalUint returns the JSON version of a Go uint.

func MarshalUint16

func MarshalUint16(value uint16) []byte

MarshalUint16 returns the JSON version of a Go uint16.

func MarshalUint32

func MarshalUint32(value uint32) []byte

MarshalUint32 returns the JSON version of a Go uint32.

func MarshalUint64

func MarshalUint64(value uint64) []byte

MarshalUint64 returns the JSON version of a Go uint64.

func MarshalUint8

func MarshalUint8(value uint8) []byte

MarshalUint8 returns the JSON version of a Go uint8.

func MergeAndMarshal

func MergeAndMarshal(values ...any) ([]byte, error)

Marshal return the JSON version of 'value'.

func StringModifierFunc

func StringModifierFunc(bytes []byte) ([]byte, error)

StringModifierFunc is the modifier that, in the DefaultUsher, is the implementation behind the "string" modifier.

For example:

struct {

	// ...

	Banana int `json:"banana,string"`

	// ...

}

func Unmarshal

func Unmarshal(data []byte, dst any) error

func UnmarshalString

func UnmarshalString(data []byte, dst *string) error

MarshalString returns the JSON version of a Go string.

Types

type Const

type Const[T any] struct{}

Const is used to include a constant field in a struct.

For example:

type AcitivtyLink struct {
	HRef            string  `json:"href"`
	MediaType       string  `json:"mediatype"`
	Rel             string  `json:"rel"`
	Rev             string  `json:"rev"`
	Type json.Const[string] `json:"type" json.value:"Link"` // <----------
}

Here is another example:

type Manitoban struct {
	GivenName               string  `json:"given-name"`
	AdditionalNames       []string  `json:"additional-names,omitempty"`
	FamilyName              string  `json:"family-name"`
	HomeCountry  json.Const[string] `json:"home-country"  json.value:"Canada"`   // <----------
	HomeProvince json.Const[string] `json:"home-province" json.value:"Manitoba"` // <----------
	HomeCity                string  `json:"home-city"`
}

func (Const[T]) DecodeFromString

func (Const[T]) DecodeFromString(str string) (any, error)

See the Constantizer interface documentation for details.

func (Const[T]) JSONConst

func (Const[T]) JSONConst()

See the Constantizer interface documentation for details on why this exists.

type Constantizer

type Constantizer interface {

	// JSONConst is a dummy-method used (along with the method DecodeFromString) to specify that something is of inteface type json.Constantizer.
	//
	// An implementation of it will look similar to this:
	//
	//	func (receiver MyType) JSONConst() {
	//		// nothing here
	//	}
	JSONConst()

	// DecodeFromString decodes the value of a string to the underlying type.
	//
	// The value will come from the value of the struct tag: "json.value".
	//
	//
	// For example:
	//
	//	type MyType struct {
	//
	//		// ...
	//
	//		MyField json.Const[uint64] `json:"myfield" json.value:"123"`
	//
	//		// ...
	//
	//	}
	DecodeFromString(string) (any, error)
}

type Emptier

type Emptier interface {
	IsEmpty() bool
}

Emptier works with the `omitempty` struct-tag, recognized by Marshal and Usher.Marshal.

For example, a custom type might look like:

type MyType struct {
	// ...
}

func (receiver MyType) IsEmpty() bool {
	// ...
}

And it might be used similar to the following:

var MyStruct struct {
	Apple  string `json:"apple,omitempty"`
	Banana MyType `json:"banana,omitempty"` // <---------
	Cherry int    `json:"cherry"`
}

// ...

var value MyStruct // = ...

bytes, err := json.Marshal(value)

An alternative to Emptier is Nothinger, which is more commonly used with optional-types (i.e., optiona-types).

type ErrorEmpty

type ErrorEmpty interface {
	error
	ErrorEmpty()
}

ErrorEmpty is a special type of error.

ErrorEmpty is used with the "omitempty" struct-field tag option.

If a (custom) type's MarshalJSON() function returns an error of type ErrorEmpty, and a field of that type has the "omitempty" struct-field tag option then, that field will be omitted in the marshaled-JSON.

You can, of course, create your own (custom) error type that fits this ErrorEmpty interface, or you can use the ErrEmpty to create that ErrorEmpty error for you.

type Marshaler

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

Marshaler is something that can marshal itself into JSON.

type ModifierFunc

type ModifierFunc func([]byte) ([]byte, error)

ModifierFunc is the type of a modifer.

Modifers as used to modify the the a marshaled struct-field.

type Nothinger

type Nothinger interface {
	IsNothing() bool
}

Nothinger is similar to Emptier, but is more commonly used with optional-types (i.e., optiona-types).

I.e., an optional-type has "something" in it or "nothing" in it. (Some optional-types call this "some" and "none".) A optional-type might have a method IsNothing()bool to communicate whether it has "nothing" or "something" in it.

If the optional-type has such a IsNothing()bool method, then Marshal and Usher.Marshal make use of that method for the purposes of `omitempty`.

If you type in not an optional-type, then it should probably instead implement Emptier.

type OmitAlways

type OmitAlways interface {
	JSONOmitAlways()
}

A field in a struct and a value in a map that fits this interface (by having the method JSONOmitAlways()) will always be omitted from the result JSON.

type Unmarshaler

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

Unmarshaler is something that can unmarshal itself from JSON.

type Usher

type Usher struct {
	// contains filtered or unexported fields
}

Usher marshals a Go type into JSON.

If you want the "string" modifier you will need to call json.Usher.ImplantModifier() to add it:

var jsonUsher json.Usher

jsonUsher.ImplantModifier("string", json.StringModifierFunc)

You can also add your own modifiers:

var jsonUsher json.Usher

jsonUsher.ImplantModifier("digest", digestFunc)
var (
	// DefaultUsher is the Usher that the json.Marshal() function uses.
	//
	// Implanting a modifier into DefaultUsher into DefaultUsher modifies how the json.Marshal() behaves.
	DefaultUsher Usher
)

func (*Usher) ImplantModifier

func (receiver *Usher) ImplantModifier(name string, fn ModifierFunc)

func (*Usher) Marshal

func (receiver *Usher) Marshal(value any) ([]byte, error)

Marshal returns the JSON version of 'value'.

omitempty

For Go structs, if a field in the struct includes the struct-tag `omitempty`, then — Marshal will NOT include its in the resulting JSON if its Go value is empty.

For example, consider:

type MyStruct struct {
	Once   string
	Twice  string `json:"twice,omitempty"` // <---------
	Thrice string `json:"thrice"`
	Fource string `json:",omitempty"`      // <---------
}

Note that field `Twice` and field `Fource` both have `omitempty` in their struct-tags. So, if their values are empty, then the resulting JSON will omit them.

For example, this:

var value MyStruct

Would (conceptually) result in:

{
	"Once":   "",
	"thrice": ""
}

And, for example, this:

var value = MyStruct{
	Once:   "",
	Twice:  "",
	Thrice: "",
	Fource: ""
}

Would also (conceptually) result in:

{
	"Once":   "",
	"thrice": ""
}

And also, for example, this:

var value = MyStruct{
	Once:   "first",
	Twice:  "second",
	Thrice: "third",
	Fource: "fourth"
}

Would (conceptually) result in:

{
	"Once":   "first",
	"twice":  "second",
	"thrice": "third",
	"Fource": "forth"
}

Custom types can also make use of Emptier or Nothinger to specify when they are empty. For example:

type MyStruct struct {
	// ...
}

func (receiver MyStruct) IsEmpty() bool {
	// ...
}

Marshal will call IsEmpty, if a custom type has it, to check whether the custom type is `empty` or not, for the purposes of `omitempty`.

func (*Usher) MergeAndMarshal

func (receiver *Usher) MergeAndMarshal(values ...any) ([]byte, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL