Documentation ¶
Overview ¶
Package payload provides utility type and functions to deal with JSON data stored as byte array. It wraps and uses awesome github.com/tidwall/sjson and github.com/tidwall/sjson packages and its types.
The main goal is to provide better switch from native json.RawMessage into gjson methods and from sjson to native json.RawMessage.
To solve this the RawMessage type introduced. It simply wraps json.RawMessage but provides proxy methods to gjson functions to get expected keys data as well as proxy methods to sjson functions to modify underlying message if required.
To simplify operations in case many keys should be set simultaneously a DataMap type is provided. It can be used with NewRawMessage or MakeRawMessage constructors as well as RawMessage.Update argument. It wraps map[string]interface{} and provides DataMap.Update methods.
IMPORTANT: see NewRawMessage description to understand difference of key and path.
Use RawMessage ¶
To build raw message from scratch use NewRawMessage or MakeRawMessage constructor or simply wrap existing json.RawMessage instance with Wrap method.
See github.com/tidwall/gjson/ documentation to details of path usage in Get and Set functions.
Index ¶
- Constants
- Variables
- func ExtendJSON(origJSON json.RawMessage, data DataMap) (result json.RawMessage, err error)
- func MakeJSON(data DataMap) (result json.RawMessage, err error)
- func MustExtendJSON(origJSON json.RawMessage, data DataMap) (result json.RawMessage)
- func MustSave(data RawMessage, path string)
- func NewJSON(data DataMap) json.RawMessage
- func Save(data RawMessage, path string) (err error)
- type DataMap
- type RawMessage
- func (r RawMessage) Exists(path string) bool
- func (r RawMessage) Get(key string) gjson.Result
- func (r RawMessage) GetBool(path string) bool
- func (r RawMessage) GetFloat64(path string) float64
- func (r RawMessage) GetInt(path string) int
- func (r RawMessage) GetString(path string) string
- func (r RawMessage) MarshalJSON() ([]byte, error)
- func (r *RawMessage) Set(key string, value interface{}) (err error)
- func (r RawMessage) String() string
- func (r *RawMessage) UnmarshalJSON(data []byte) error
- func (r *RawMessage) Update(data DataMap) error
Examples ¶
Constants ¶
const EmptyJSONObject = "{}"
EmptyJSONObject contains empty JSON object string representation.
Variables ¶
var Error = errors.New("encode")
Error indicates payload routines errors.
Functions ¶
func ExtendJSON ¶
func ExtendJSON(origJSON json.RawMessage, data DataMap) (result json.RawMessage, err error)
ExtendJSON extend existing raw JSON message of json.RawMessage with specified data, doing keys unpacking by dot separator, f.e. pair "a.b.c": true became a>b>c=true. If creating new message from keys use normalizeKeys.
func MakeJSON ¶
func MakeJSON(data DataMap) (result json.RawMessage, err error)
MakeJSON prepares json.RawMessage suitable to use as request data or response result. If any key contains dot it became multilayer key f.e. pair "a.b.c": true became a>b>c=true. It is a shorthand to call ExtendJSON([]byte(EmptyJSONObject), ...).
func MustExtendJSON ¶
func MustExtendJSON(origJSON json.RawMessage, data DataMap) (result json.RawMessage)
MustExtendJSON extend existing raw JSON message of json.RawMessage with specified data, doing keys unpacking by dot separator, f.e. pair "a.b.c": true became a>b>c=true. If creating new message from keys use normalizeKeys. Panics if error happened during raw JSON updating.
func MustSave ¶
func MustSave(data RawMessage, path string)
MustSave saves RawMessage data into specified file path. Panics if save failed.
func NewJSON ¶
func NewJSON(data DataMap) json.RawMessage
NewJSON prepares json.RawMessage suitable to use as request data or response result. If any key contains dot it became multilayer key f.e. pair "a.b.c": true became a>b>c=true. It is a shorthand to call ExtendJSON([]byte(EmptyJSONObject), ...). Panics if error happened during raw JSON creation.
func Save ¶
func Save(data RawMessage, path string) (err error)
Save stores RawMessage data into specified file path. Returns error if save failed.
Types ¶
type RawMessage ¶
type RawMessage json.RawMessage
RawMessage extends basic json.RawMessage with extraction and manipulation methods of gjson/sjson.
func Load ¶
func Load(path string) (data RawMessage, err error)
Load loads payload.RawMessage message from specified path. Returns loaded RawMessage data or load error.
func MakeRawMessage ¶
func MakeRawMessage(data DataMap) (r *RawMessage, err error)
MakeRawMessage creates new RawMessage using specified data mapping. Returns error if underlying conversion failed. If you need json.RawMessage with error instead use utility function MakeJSON.
Example ¶
package main import ( "fmt" "log" "github.com/amarin/payload" ) func main() { // make new empty MakeMessage with error handling rawJSON, err := payload.MakeRawMessage(nil) if err != nil { log.Fatal("MakeRawMessage:", err) } fmt.Println(rawJSON.String()) // make new RawMessage with single string value newRawJSON, err := payload.MakeRawMessage(payload.DataMap{"intKey": 10}) if err != nil { log.Fatal("MakeRawMessage:", err) } fmt.Println(newRawJSON.String()) // take string value using known key stringKey := newRawJSON.GetInt("intKey") fmt.Println(stringKey) }
Output: {} {"intKey":10} 10
func MustLoad ¶
func MustLoad(path string) (data RawMessage)
MustLoad loads payload.RawMessage message from specified file path. Panics if load failed.
func NewRawMessage ¶
func NewRawMessage(data DataMap) (r *RawMessage)
NewRawMessage creates new RawMessage using specified data mapping. Panics if underlying conversion failed. If you need json.RawMessage result use utility function NewJSON which do everything required under the hood. Provided data should contain flat mapping of path->value pairs where path is in dot syntax, such as "name.last" or "age". When the value is found it's returned immediately. A path is a series of keys separated by a dot. A key may contain special wildcard characters '*' and '?'. To access an array value use the index as the key. To get the number of elements in an array or to access a child path, use the '#' character. The dot and wildcard character can be escaped with '\'.
Example ¶
package main import ( "fmt" "github.com/amarin/payload" ) func main() { // make new empty RawMessage rawJSON := payload.NewRawMessage(nil) fmt.Println(rawJSON.String()) // make new RawMessage with single string value newRawJSON := payload.NewRawMessage(payload.DataMap{"stringKey": "stringValue"}) fmt.Println(newRawJSON.String()) // take string value using known key stringKey := newRawJSON.GetString("stringKey") fmt.Println(stringKey) }
Output: {} {"stringKey":"stringValue"} stringValue
func Wrap ¶
func Wrap(message json.RawMessage) (r *RawMessage)
Wrap makes an RawMessage from provided json.RawMessage. It's a simple wrapper around RawMessage(message).
Example ¶
package main import ( "fmt" "github.com/amarin/payload" ) func main() { rawMessage := payload.Wrap([]byte(`{"intKey":1,"boolKey":true,"stringKey":"iAmAString"}`)) fmt.Println( rawMessage.GetInt("intKey"), rawMessage.GetBool("boolKey"), rawMessage.GetString("stringKey"), ) // Output // 1 true iAmAString }
Output:
func (RawMessage) Exists ¶
func (r RawMessage) Exists(path string) bool
Exists returns true if specified key path exists in request params. Path may be search query, see https://github.com/tidwall/gjson for detailed info.
func (RawMessage) Get ¶
func (r RawMessage) Get(key string) gjson.Result
Get returns gjson.Result value taken from payload by specified path. Path may be search query, see https://github.com/tidwall/gjson for detailed info.
func (RawMessage) GetBool ¶
func (r RawMessage) GetBool(path string) bool
GetBool returns bool value taken from request params by specified path. Path may be search query, see https://github.com/tidwall/gjson for detailed info. If specified key empty or not exists returns false. To check if key exists use Exists or get raw result with Get. NOTE: for non-boolean values if called for numeric field it returns false if value=0 and true otherwise. For string field it returns false if string is empty, equals "0" or "false" and true otherwise.
func (RawMessage) GetFloat64 ¶
func (r RawMessage) GetFloat64(path string) float64
GetFloat64 returns float64 value taken from request params by specified path. Path may be search query, see https://github.com/tidwall/gjson for detailed info. If specified key empty or not exists returns 0. To check if key exists use Exists or get raw result with Get.
func (RawMessage) GetInt ¶
func (r RawMessage) GetInt(path string) int
GetInt returns int value taken from request params by specified path. Path may be search query, see https://github.com/tidwall/gjson for detailed info. If specified key empty or not exists returns 0. To check if key exists use Exists or get raw result with Get.
func (RawMessage) GetString ¶
func (r RawMessage) GetString(path string) string
GetString returns string value taken from request params by specified path. Path may be search query, see https://github.com/tidwall/gjson for detailed info. If specified key empty or not exists returns empty string. To check if key exists use Exists or get raw result with Get.
func (RawMessage) MarshalJSON ¶
func (r RawMessage) MarshalJSON() ([]byte, error)
MarshalJSON does json marshalling of raw message. Implements json.Marshaler.
func (*RawMessage) Set ¶
func (r *RawMessage) Set(key string, value interface{}) (err error)
Set updates RawMessage adding or modifying specified key value.
func (RawMessage) String ¶
func (r RawMessage) String() string
String returns string representation of RawData. Implements fmt.Stringer.
func (*RawMessage) UnmarshalJSON ¶
func (r *RawMessage) UnmarshalJSON(data []byte) error
UnmarshalJSON does json unmarshalling of raw message. Implements json.Unmarshaler.
func (*RawMessage) Update ¶
func (r *RawMessage) Update(data DataMap) error
Update updates RawMessage in place adding or modifying keys from specified DataMap.