swallowjson: go.pennock.tech/swallowjson Index | Files

package swallowjson

import "go.pennock.tech/swallowjson"

Package swallowjson provides a utility function for implementing the encoding/json.Unmarshaler interface's UnmarshalJSON method to decode, without discarding unknown keys. The "swallow" concept says that any keys in a JSON object which do not correspond to a known field in a (Golang) struct should not be discarded but instead put into a map.

type MyType struct {
	Foo  string                 `json:"foo"`
	Bar  int                    `json:"bar"`
	Rest map[string]interface{} `json:"-"`
}

func (mt *MyType) UnmarshalJSON(raw []byte) error {
	return swallowjson.UnmarshalWith(mt, "Rest", raw)
}

The struct field to swallow fields not explicitly named must be a map keyed by string. The type of map values is handled reliably, returning a JSON error if unsuitable. Common types to use might be `interface{}` or `json.RawMessage`.

Errors are either of type swallowjson.SwallowError or are bubbled through from the json or reflect packages.

Index

Package Files

decode.go

Variables

var (
    ErrGivenNonStringKey       = SwallowError{s: "given object with non-string key"}
    ErrMalformedJSON           = SwallowError{s: "given malformed JSON"}
    ErrMissingSpilloverField   = SwallowError{s: "target struct missing specified spillover field"}
    ErrNotGivenMutable         = SwallowError{s: "not given something which we can assign to"}
    ErrNotGivenStruct          = SwallowError{s: "not given a struct in the raw stream"}
    ErrNotStructHolder         = SwallowError{s: "holder is not a struct"}
    ErrSpillNotRightMap        = SwallowError{s: "target's spillover field is not a map[string]interface{}"}
    ErrUnsetableSpilloverField = SwallowError{s: "target struct's spillover field not assignable"}
)

These errors may be returned by UnmarshalWith.

func UnmarshalWith Uses

func UnmarshalWith(target interface{}, spilloverName string, raw []byte) error

UnmarshalWith is used for implementing UnmarshalJSON methods to satisfy the encoding/json.Unmarshaler interface. The method becomes a one-liner returning the result of calling this function, supplying in addition to the object and input only the name of the field which should swallow unknown JSON fields.

type SwallowError Uses

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

SwallowError is the type of all errors generated within the swallowjson package. Errors will either be of this type, or bubbled through. The string representation of the error is guaranteed to start "swallowjson:".

func (SwallowError) Error Uses

func (se SwallowError) Error() string

Package swallowjson imports 5 packages (graph). Updated 2018-03-19. Refresh now. Tools for package owners.