Documentation ¶
Index ¶
- Constants
- Variables
- func Extract(search []byte, path string) ([]byte, string, error)
- func ExtractBool(search []byte, path string) (bool, error)
- func ExtractFloat(search []byte, path string) (float64, error)
- func ExtractInt(search []byte, path string) (int, error)
- func ExtractInterface(search []byte, path string) (interface{}, string, error)
- func ExtractString(search []byte, path string) (string, error)
- func GetJSONType(search []byte, start int) string
- func GetJSONTypeStrict(search []byte, start int) string
- func Indent(b []byte) bytes.Buffer
- func IsEmptyArray(b []byte) bool
- func IsEmptyObject(b []byte) bool
- func IsJSON(b []byte) bool
- func IsJSONArray(b []byte) bool
- func IsJSONFalse(b []byte) bool
- func IsJSONNull(b []byte) bool
- func IsJSONNumber(b []byte) bool
- func IsJSONObject(b []byte) bool
- func IsJSONString(b []byte) bool
- func IsJSONTrue(b []byte) bool
- func MergeJSON(base, patch []byte) ([]byte, error)
- func PanicRecovery(err *error)
- func Unmarshal(raw []byte, v interface{}) (err error)
- func UnmarshalStrict(raw []byte, v interface{}) (err error)
- type Iterator
- type JSONReader
- func (jr *JSONReader) Get(key string) *JSONReader
- func (jr *JSONReader) GetBool(key string) bool
- func (jr *JSONReader) GetBoolSlice(key string) []bool
- func (jr *JSONReader) GetByteSlice(key string) []byte
- func (jr *JSONReader) GetByteSlices(key string) [][]byte
- func (jr *JSONReader) GetCollection(key string) []JSONReader
- func (jr *JSONReader) GetFloat(key string) float64
- func (jr *JSONReader) GetFloatSlice(key string) []float64
- func (jr *JSONReader) GetInt(key string) int
- func (jr *JSONReader) GetIntSlice(key string) []int
- func (jr *JSONReader) GetInterface(key string) interface{}
- func (jr *JSONReader) GetInterfaceSlice(key string) []interface{}
- func (jr *JSONReader) GetMapStringInterface(key string) map[string]interface{}
- func (jr *JSONReader) GetString(key string) string
- func (jr *JSONReader) GetStringSlice(key string) []string
- func (jr *JSONReader) KeyExists(key string) bool
- func (jr *JSONReader) ToBool() bool
- func (jr *JSONReader) ToBoolSlice() []bool
- func (jr *JSONReader) ToByteSlice() []byte
- func (jr *JSONReader) ToByteSlices() [][]byte
- func (jr *JSONReader) ToFloat() float64
- func (jr *JSONReader) ToFloatSlice() []float64
- func (jr *JSONReader) ToInt() int
- func (jr *JSONReader) ToIntSlice() []int
- func (jr *JSONReader) ToInterface() interface{}
- func (jr *JSONReader) ToInterfaceSlice() []interface{}
- func (jr *JSONReader) ToMapStringBool() map[string]bool
- func (jr *JSONReader) ToMapStringBytes() map[string][]byte
- func (jr *JSONReader) ToMapStringFloat() map[string]float64
- func (jr *JSONReader) ToMapStringInt() map[string]int
- func (jr *JSONReader) ToMapStringInterface() map[string]interface{}
- func (jr *JSONReader) ToMapStringString() map[string]string
- func (jr *JSONReader) ToString() string
- func (jr *JSONReader) ToStringSlice() []string
- type PostUnmarshaler
- type StructDescriptor
- type StructKey
Constants ¶
const ( // JSONNull denotes JSON value 'null' JSONNull = "null" // JSONBool denotes JSON values 'true' or 'false' JSONBool = "bool" // JSONInt denotes a JSON integer JSONInt = "int" // JSONFloat denotes a JSON floating point value JSONFloat = "float" // JSONString denotes a JSON string JSONString = "string" // JSONArray denotes a JSON array JSONArray = "array" // JSONObject denotes a JSON object JSONObject = "object" // JSONInvalid denotes a value that is not valid JSON JSONInvalid = "" )
Variables ¶
var ( // ErrEndOfInput is returned when there are no further items to extract via Next() ErrEndOfInput = errors.New("Reached end of JSON Input") // ErrNoSuchIndex is returned when Index(n) is called and n does not exist. ErrNoSuchIndex = errors.New("Index does not exist") // ErrRequiresObject is returned when the input is neither an array or object. ErrRequiresObject = errors.New("NewIterator requires a valid JSONArray or JSONObject") )
var ( // ErrEmpty is returned when no input is provided. ErrEmpty = errors.New("empty input value") // ErrMalformedJSON is returned when input failed to parse. ErrMalformedJSON = errors.New("malformed json provided") )
var ( // ErrMergeType is returned when MergeJSON receives anything other than JSONObject or JSONArray ErrMergeType = errors.New("only JSONObject can be merged") )
Functions ¶
func Extract ¶
Extract a specific key from a given JSON string. Returns value, type, and error.
Key Path Values: String, Number, and Constant not in a surrounding array or object will always
return the root, regardless of the key given.
Arrays will index from 0. Objects will will index as they are keyed. Empty key will always return whatever is at the root. Path is a period separated list of keys.
Examples:
data := []byte(`{ "active": 0, "url": "http://www.example.com", "metadata": { "keywords": [ "example", "sample", "illustration", ], "error_code": 0 } }`)
Extract(data, "active") returns 0, "int", nil Extract(data, "url") returns "http://www.example.com", "string", nil Extract(data, "metadata.keywords.1") returns []byte(`"sample"`), "string", nil Extract(data, "metadata.error_code") returns []byte{'0'}, "int", nil Extract(data, "metadata.keywords.17") returns []byte(nil), "", "requested key 'metadata.keywords.17' doesn't exist
On return, a copy is made of the extracted data. This allows it to be modified without changing the original JSON.
func ExtractBool ¶
ExtractBool performs an Extract on the given JSON path. The resulting value is returned in the form of a bool. Numeric values are considered true if they are non-zero. String values are evaluated using strings.ParseBool. null is always false.
func ExtractFloat ¶
ExtractFloat performs an Extract on the given JSON path. The resulting value is returned in the form of a float64.
func ExtractInt ¶
ExtractInt performs an Extract on the given JSON path. The resulting value is returned in the form of an int.
func ExtractInterface ¶
ExtractInterface performs an Extract on the given JSON path. The resulting value is returned in the form defined below. The returned type is the JSON type. These map as follows: json type -> interface{} type
JSONInt -> int JSONFloat -> float64 JSONString -> string JSONBool -> bool JSONNull -> interface{}(nil) JSONArray -> []interface{} JSONObject -> map[string]interface{}
func ExtractString ¶
ExtractString performs an Extract on the given JSON path. The resulting value is returned in the form of a string.
func GetJSONType ¶
GetJSONType inspects the given byte string and attempts to identify the primary JSON type. JSONString, JSONInt, JSONFloat, JSONBool, JSONNull, JSONObject, or JSONArray JSONInvalid ("") denotes a JSON error.
Note that this is an early return guess. It's not guaranteed accurate if you send invalid JSON, as very little validation is performed for the sake of speed.
e.g. GetJSONType([]byte(`"No End Quote`), 0) would return JSONString, NOT JSONInvalid, despite the fact that the given data is invalid JSON.
If you must validate that you have valid JSON, call IsJSON with your byte string prior to calling GetJSONType. Or call GetJSONTypeStrict.
func GetJSONTypeStrict ¶
GetJSONTypeStrict validates the given byte string as JSON and returns the primary JSON type. JSONString, JSONInt, JSONFloat, JSONBool, JSONNull, JSONObject, or JSONArray JSONInvalid ("") denotes a JSON error.
GetJSONTypeStrict WILL perform JSON Validation, and return JSONInvalid if that validation fails. This is slower than GetJSONType due to the extra validation involved.
func IsEmptyArray ¶
IsEmptyArray returns true if the given JSON is an empty array.
func IsEmptyObject ¶
IsEmptyObject returns true if the given JSON is an empty object.
func IsJSON ¶
IsJSON performs validation on a JSON string.
JSON = null
or true or false or JSONNumber or JSONString or JSONObject or JSONArray
func IsJSONArray ¶
IsJSONArray validates a string as a JSON Array.
JSONArray = [ ]
or [ ArrayElements ]
func IsJSONFalse ¶
IsJSONFalse returns true if the byte array is a JSON false value.
func IsJSONNull ¶
IsJSONNull returns true if the byte array is a JSON null value.
func IsJSONNumber ¶
IsJSONNumber validates a string as a JSON Number.
JSONNumber = - PositiveNumber
or PositiveNumber
PositiveNumber = DecimalNumber
or DecimalNumber . Digits or DecimalNumber . Digits ExponentPart or DecimalNumber ExponentPart
DecimalNumber = 0
or OneToNine Digits
ExponentPart = e Exponent
or E Exponent
Exponent = Digits
or + Digits or - Digits
Digits = Digit
or Digits Digit
Digit = 0 through 9 OneToNine = 1 through 9
func IsJSONObject ¶
IsJSONObject validates a string as a JSON Object.
JSONObject = { }
or { Members }
func IsJSONString ¶
IsJSONString validates a string as a JSON String.
JSONString = ""
or " StringCharacters "
func IsJSONTrue ¶
IsJSONTrue returns true if the byte array is a JSON true value.
func MergeJSON ¶ added in v1.0.7
MergeJSON merges two JSONObject together and returns the combination. Base and Patch must be type JSONObject. When keys exist in the base but not in the patch, it will be retained. When keys exist in the patch but not in the base, it will be added to the base. JSONArray, JSONString, JSONInt, JSONFloat, JSONNull in the patch will always override the base. JSONObject in the patch will override anything but JSONObject in the base. JSONObject in the patch AND JSONObject in the base will be merged together.
func PanicRecovery ¶
func PanicRecovery(err *error)
PanicRecovery returns a general use Panic Recovery function to capture panics and returns them as errors. A pointer to the error to populate will be passed in via the err parameter. err must be addressable.
usage: defer PanicRecovery(&err)()
func Unmarshal ¶
Unmarshal takes a json format byte string and extracts it into the given container.
func UnmarshalStrict ¶
UnmarshalStrict takes a json format byte string and extracts it into the given container using strict standards for type association.
Types ¶
type Iterator ¶
type Iterator struct {
// contains filtered or unexported fields
}
Iterator receives a raw JSONArray or JSONObject, and provides an interface for extracting each member item one-by-one.
func NewIterator ¶
NewIterator returns a primed Iterator
func (*Iterator) Index ¶
Index moves the internal counter to AFTER the specified member position, and returns the data in that member position. Positions are zero-based, so the first member is Index(0). Note that this means Last() will return the same data as Index(n) when called immediately after Index.
func (*Iterator) Last ¶
Last returns the most recently accessed member element in the container, or the first element if never accessed.
type JSONReader ¶
type JSONReader struct { // Keys holds the list of top-level keys Keys []string // Type is the JSONType of the top-level data. Type string // Empty is true if parsing failed or no data was supplied. Empty bool // StrictStandards directs the extraction functions to be strict with type // casting and extractions where applicable. StrictStandards bool // contains filtered or unexported fields }
JSONReader Provides utility functions for manipulating json structures.
func ExtractReader ¶
func ExtractReader(search []byte, path string) (*JSONReader, error)
ExtractReader performs an Extract on the given JSON path. The resulting value is returned in the form of a JSONReader primed with the value returned from Extract.
func NewJSONReader ¶
func NewJSONReader(rawData []byte) (reader *JSONReader, err error)
NewJSONReader creates a new JSONReader object, which parses the rawData input and provides access to various accessor functions useful for working with JSONData.
Behavior is undefined when a JSONReader is created via means other than NewJSONReader.
func (*JSONReader) Get ¶
func (jr *JSONReader) Get(key string) *JSONReader
Get retrieves a nested object and returns a JSONReader with the root containing the contents of the delved key.
func (*JSONReader) GetBool ¶
func (jr *JSONReader) GetBool(key string) bool
GetBool retrieves a given key as boolean, if it exists.
func (*JSONReader) GetBoolSlice ¶
func (jr *JSONReader) GetBoolSlice(key string) []bool
GetBoolSlice retrieves a given key as a bool slice, if it exists.
func (*JSONReader) GetByteSlice ¶
func (jr *JSONReader) GetByteSlice(key string) []byte
GetByteSlice returns the given key and all child elements as a byte array.
func (*JSONReader) GetByteSlices ¶
func (jr *JSONReader) GetByteSlices(key string) [][]byte
GetByteSlices retrieves a given key as a slice of byte slices, if it exists.
func (*JSONReader) GetCollection ¶
func (jr *JSONReader) GetCollection(key string) []JSONReader
GetCollection extracts a nested JSONArray and returns a slice of JSONReader, with one JSONReader for each element in the JSONArray.
func (*JSONReader) GetFloat ¶
func (jr *JSONReader) GetFloat(key string) float64
GetFloat retrieves a given key as float64, if it exists.
func (*JSONReader) GetFloatSlice ¶
func (jr *JSONReader) GetFloatSlice(key string) []float64
GetFloatSlice retrieves a given key as a float64 slice, if it exists.
func (*JSONReader) GetInt ¶
func (jr *JSONReader) GetInt(key string) int
GetInt retrieves a given key as an int, if it exists.
func (*JSONReader) GetIntSlice ¶
func (jr *JSONReader) GetIntSlice(key string) []int
GetIntSlice retrieves a given key as a int slice, if it exists.
func (*JSONReader) GetInterface ¶
func (jr *JSONReader) GetInterface(key string) interface{}
GetInterface returns the data given key as an interface{} based on the JSONType of the data.
func (*JSONReader) GetInterfaceSlice ¶
func (jr *JSONReader) GetInterfaceSlice(key string) []interface{}
GetInterfaceSlice returns the given key as an interface{} slice.
func (*JSONReader) GetMapStringInterface ¶
func (jr *JSONReader) GetMapStringInterface(key string) map[string]interface{}
GetMapStringInterface retrieves a given key as a map of string onto interface{}, if said key exists.
func (*JSONReader) GetString ¶
func (jr *JSONReader) GetString(key string) string
GetString retrieves a given key as a string, if it exists.
func (*JSONReader) GetStringSlice ¶
func (jr *JSONReader) GetStringSlice(key string) []string
GetStringSlice retrieves a given key as a string slice, if it exists.
func (*JSONReader) KeyExists ¶
func (jr *JSONReader) KeyExists(key string) bool
KeyExists returns true if a given key exists in the parsed json.
func (*JSONReader) ToBool ¶
func (jr *JSONReader) ToBool() bool
ToBool returns the top-level JSON into an integer.
func (*JSONReader) ToBoolSlice ¶
func (jr *JSONReader) ToBoolSlice() []bool
ToBoolSlice returns all top-level data as a bool slice.
func (*JSONReader) ToByteSlice ¶
func (jr *JSONReader) ToByteSlice() []byte
ToByteSlice returns all top-level data as a byte slice.
func (*JSONReader) ToByteSlices ¶
func (jr *JSONReader) ToByteSlices() [][]byte
ToByteSlices returns all top-level data as a slice of byte slices.
func (*JSONReader) ToFloat ¶
func (jr *JSONReader) ToFloat() float64
ToFloat returns the top-level JSON into a float64.
func (*JSONReader) ToFloatSlice ¶
func (jr *JSONReader) ToFloatSlice() []float64
ToFloatSlice returns all top-level data as a float64 slice.
func (*JSONReader) ToInt ¶
func (jr *JSONReader) ToInt() int
ToInt returns the top-level JSON into an integer.
func (*JSONReader) ToIntSlice ¶
func (jr *JSONReader) ToIntSlice() []int
ToIntSlice returns all top-level data as a int slice.
func (*JSONReader) ToInterface ¶
func (jr *JSONReader) ToInterface() interface{}
ToInterface returns the top-level JSON as an interface{} based on the JSONType of the data.
func (*JSONReader) ToInterfaceSlice ¶
func (jr *JSONReader) ToInterfaceSlice() []interface{}
ToInterfaceSlice returns all top-level data as an interface{} slice.
func (*JSONReader) ToMapStringBool ¶
func (jr *JSONReader) ToMapStringBool() map[string]bool
ToMapStringBool returns all top-level data as map of string onto bool.
func (*JSONReader) ToMapStringBytes ¶
func (jr *JSONReader) ToMapStringBytes() map[string][]byte
ToMapStringBytes returns all top-level data as map of string onto []byte.
func (*JSONReader) ToMapStringFloat ¶
func (jr *JSONReader) ToMapStringFloat() map[string]float64
ToMapStringFloat returns all top-level data as map of string onto float64.
func (*JSONReader) ToMapStringInt ¶
func (jr *JSONReader) ToMapStringInt() map[string]int
ToMapStringInt returns all top-level data as map of string onto int.
func (*JSONReader) ToMapStringInterface ¶
func (jr *JSONReader) ToMapStringInterface() map[string]interface{}
ToMapStringInterface retrieves a given key as a map of string onto interface{}, if said key exists.
func (*JSONReader) ToMapStringString ¶
func (jr *JSONReader) ToMapStringString() map[string]string
ToMapStringString returns all top-level data as map of string onto string.
func (*JSONReader) ToString ¶
func (jr *JSONReader) ToString() string
ToString returns the top-level JSON as a string.
func (*JSONReader) ToStringSlice ¶
func (jr *JSONReader) ToStringSlice() []string
ToStringSlice returns all top-level data as a string slice.
type PostUnmarshaler ¶
PostUnmarshaler is the interface implemented by types that can perform actions after Unmarshal / UnmarshalJSON has finished. This allows you to inspect the results and make corrections / adjustments / error checking after the unmarshaler has finished its work. An example use case is checking whether a slice is nil after unmarshal.
Errors returned from PostUnmarshalJSON executed by the Unmarshal function (rather than called explicitly) will be ignored, UNLESS that error is included as the parameter to a panic. A panic inside PostUnmarshalJSON will be returned as the error return value from Unmarshal's PanicRecovery functionality.
type StructDescriptor ¶
type StructDescriptor struct { Keys map[string]StructKey RequiredKeys []string NonEmptyKeys []string // KeyMap links alternate names for a field onto a "primary" field. KeyMap map[string]string }
StructDescriptor holds parsed metadata about a given struct.
func (*StructDescriptor) NonEmpty ¶
func (d *StructDescriptor) NonEmpty(key string) bool
NonEmpty returns true if a key is required to be NonEmpty
func (*StructDescriptor) Required ¶
func (d *StructDescriptor) Required(key string) bool
Required returns true if a key is required to exist
type StructKey ¶
type StructKey struct { // Type is the type of the struct key. Type reflect.Type // Kind is the kind of the struct key. Kind reflect.Kind // Name is the primary name for the given struct key. Name string // Index is the position in the struct where the given field can be found. Index int // Path maintains the path we need to traverse through struct keys to resolve embeded keys. Path []int }
StructKey provides information about a single field in a struct