Documentation ¶
Overview ¶
Package gson provide a toolkit for JSON representation, collation and transformation.
Package provides APIs to convert data representation from one format to another. Supported formats are:
- JSON
- Golang value
- CBOR - Concise Binary Object Representation
- Binary-collation
CBOR:
Concise Binary Object Representation, CBOR, is based on RFC-7049 specification to encode golang data into machine friendly format. Following golang native types are supported:
- nil, true, false.
- native integer types, and its alias, of all width.
- float32, float64.
- slice of bytes.
- native string.
- slice of interface - []interface{}.
- map of string to interface{} - map[string]interface{}.
Types from golang's standard library and custom types provided by this package that can be encoded using CBOR:
- CborTagBytes: a cbor encoded []bytes treated as value.
- CborUndefined: encode a data-item as undefined.
- CborIndefinite: encode bytes, string, array and map of unspecified length.
- CborBreakStop: to encode end of CborIndefinite length item.
- CborTagEpoch: in seconds since epoch.
- CborTagEpochMicro: in micro-seconds epoch.
- CborTagFraction: m*(10**e)
- CborTagFloat: m*(2**e)
- CborTagPrefix: to self identify a binary blog as CBOR.
Package also provides an implementation for encoding JSON to CBOR and vice-versa:
- Number can be encoded as integer or float.
- Arrays and maps are encoded using indefinite encoding.
- Byte-string encoding is not used.
Json-Pointer:
Package also provides a RFC-6901 (JSON-pointers) implementation.
NOTE: Buffer supplied to APIs NewJson(), NewCbor(), NewCollate() should atleast be 128 bytes in size.
Index ¶
- Constants
- Variables
- func CborMap2golangMap(value interface{}) interface{}
- func Fixtojson(config *Config, val interface{}) interface{}
- func GolangMap2cborMap(value interface{}) interface{}
- type Cbor
- func (cbr *Cbor) Append(jptr *Jsonpointer, item, newdoc *Cbor) *Cbor
- func (cbr *Cbor) Bytes() []byte
- func (cbr *Cbor) Delete(jptr *Jsonpointer, newdoc, deleted *Cbor) *Cbor
- func (cbr *Cbor) EncodeBytechunks(chunks [][]byte) *Cbor
- func (cbr *Cbor) EncodeMapslice(items [][2]interface{}) *Cbor
- func (cbr *Cbor) EncodeSimpletype(typcode byte) *Cbor
- func (cbr *Cbor) EncodeSmallint(item int8) *Cbor
- func (cbr *Cbor) EncodeTextchunks(chunks []string) *Cbor
- func (cbr *Cbor) Get(jptr *Jsonpointer, item *Cbor) *Cbor
- func (cbr *Cbor) Prepend(jptr *Jsonpointer, item, newdoc *Cbor) *Cbor
- func (cbr *Cbor) Reset(data []byte) *Cbor
- func (cbr *Cbor) Set(jptr *Jsonpointer, item, newdoc, old *Cbor) *Cbor
- func (cbr *Cbor) Tocollate(clt *Collate) *Collate
- func (cbr *Cbor) Tojson(jsn *Json) *Json
- func (cbr *Cbor) Tovalue() interface{}
- type CborBreakStop
- type CborIndefinite
- type CborTagBytes
- type CborTagEpoch
- type CborTagEpochMicro
- type CborTagFloat
- type CborTagFraction
- type CborTagPrefix
- type CborUndefined
- type Collate
- type Config
- func (config *Config) NewCbor(buffer []byte) *Cbor
- func (config *Config) NewCollate(buffer []byte) *Collate
- func (config *Config) NewJson(buffer []byte) *Json
- func (config *Config) NewJsonpointer(path string) *Jsonpointer
- func (config *Config) NewValue(value interface{}) *Value
- func (config Config) ResetPools(strlen, numkeys, itemlen, ptrlen int) *Config
- func (config Config) SetContainerEncoding(ct ContainerEncoding) *Config
- func (config Config) SetJptrlen(n int) *Config
- func (config Config) SetMaxkeys(n int) *Config
- func (config Config) SetNumberKind(nk NumberKind) *Config
- func (config Config) SetSpaceKind(ws SpaceKind) *Config
- func (config Config) SetStrict(what bool) *Config
- func (config Config) SetTextCollator(collator *collate.Collator) *Config
- func (config Config) SortbyArrayLen(what bool) *Config
- func (config Config) SortbyPropertyLen(what bool) *Config
- func (config *Config) String() string
- func (config Config) UseMissing(what bool) *Config
- type ContainerEncoding
- type Json
- type Jsonpointer
- type Missing
- type NumberKind
- type SpaceKind
- type Value
- func (val *Value) Append(jptr *Jsonpointer, item interface{}) interface{}
- func (val *Value) Compare(other *Value) int
- func (val *Value) Data() interface{}
- func (val *Value) Delete(jptr *Jsonpointer) (newval, deleted interface{})
- func (val *Value) Get(jptr *Jsonpointer) (item interface{})
- func (val *Value) ListPointers(ptrs []string) []string
- func (val *Value) Prepend(jptr *Jsonpointer, item interface{}) interface{}
- func (val *Value) Set(jptr *Jsonpointer, item interface{}) (newval, oldval interface{})
- func (val *Value) Tocbor(cbr *Cbor) *Cbor
- func (val *Value) Tocollate(clt *Collate) *Collate
- func (val *Value) Tojson(jsn *Json) *Json
Examples ¶
Constants ¶
const CborMaxSmallInt = 23
CborMaxSmallInt maximum integer value that can be stored as associative value for cborType0 or cborType1.
const MissingLiteral = Missing("~[]{}falsenilNA~")
MissingLiteral is undocumented, for now.
Variables ¶
var ( Terminator byte = 0 TypeMissing byte = 49 TypeNull byte = 50 TypeFalse byte = 60 TypeTrue byte = 70 TypeNumber byte = 80 TypeString byte = 90 TypeLength byte = 100 TypeArray byte = 110 TypeObj byte = 120 TypeBinary byte = 130 )
Collation order for supported types. Applications desiring different ordering between types can initialize these byte values before instantiating a config object.
var MaxCollateLen = 1024 * 1024
MaxCollateLen maximum length of collated value. Affects memory pool. Changing this value will affect all new configuration instances.
var MaxJsonpointerLen = 2048
MaxJsonpointerLen size of json-pointer path. Affects memory pool. Changing this value will affect all new configuration instances.
var MaxKeys = 1024
MaxKeys maximum number of keys allowed in a property object. Affects memory pool. Changing this value will affect all new configuration instances.
var MaxStringLen = 1024 * 1024
MaxStringLen maximum length of string value inside json document. Affects memory pool. Changing this value will affect all new configuration instances.
Functions ¶
func CborMap2golangMap ¶
func CborMap2golangMap(value interface{}) interface{}
CborMap2golangMap used by validation tools. Transforms [][2]interface{} to map[string]interface{} that is required for converting golang to cbor and vice-versa.
func Fixtojson ¶
func Fixtojson(config *Config, val interface{}) interface{}
Fixtojson used by validation tools.
func GolangMap2cborMap ¶
func GolangMap2cborMap(value interface{}) interface{}
GolangMap2cborMap used by validation tools. Transforms map[string]interface{} to [][2]interface{} that is required for converting golang to cbor and vice-versa.
Types ¶
type Cbor ¶
type Cbor struct {
// contains filtered or unexported fields
}
Cbor encapsulates configuration and a cbor buffer. Use config object's NewCbor() method to Create new instance of Cbor. Map element in cbor encoding should have its keys sorted.
Example ¶
config := NewDefaultConfig() cbr := config.NewCbor(make([]byte, 0, 128)) val1 := [][]byte{[]byte("hello"), []byte("world")} cbr.EncodeBytechunks(val1) fmt.Printf("value: %v cbor: %q\n", val1, cbr.Bytes()) cbr.Reset(nil) val2 := [][2]interface{}{{"first", true}} cbr.EncodeMapslice(val2) fmt.Printf("value: %v cbor: %q\n", val2, cbr.Bytes()) cbr.Reset(nil) val3, val4 := byte(128), int8(-10) cbr.EncodeSimpletype(val3).EncodeSmallint(val4) fmt.Printf("value: {%v,%v} cbor: %q\n", val3, val4, cbr.Bytes()) cbr.Reset(nil) val5 := []string{"sound", "ok", "horn"} cbr.EncodeTextchunks(val5) fmt.Printf("value: %v cbor: %q\n", val5, cbr.Bytes()) cbr.Reset(nil) config = NewDefaultConfig() cbr = config.NewCbor(make([]byte, 0, 1024)) jsn := config.NewJson(make([]byte, 0, 1024)) clt := config.NewCollate(make([]byte, 0, 1024)) config.NewValue([]interface{}{10, 20, 100}).Tocbor(cbr) fmt.Printf("to json : %q\n", cbr.Tojson(jsn).Bytes()) fmt.Printf("to collate: %q\n", cbr.Tocollate(clt).Bytes()) fmt.Printf("to value : %v\n", cbr.Tovalue())
Output: value: [[104 101 108 108 111] [119 111 114 108 100]] cbor: "_EhelloEworld\xff" value: [[first true]] cbor: "efirst\xf5" value: {128,-10} cbor: "\xf8\x80)" value: [sound ok horn] cbor: "\u007fesoundbokdhorn\xff" to json : "[10,20,100]" to collate: "nP>>21-\x00P>>22-\x00P>>31-\x00\x00" to value : [10 20 100]
func (*Cbor) Append ¶
func (cbr *Cbor) Append(jptr *Jsonpointer, item, newdoc *Cbor) *Cbor
Append item at the end of an array field specified by json-pointer.
Example ¶
config := NewDefaultConfig() cbr1 := config.NewCbor(make([]byte, 0, 1024)) cbr2 := config.NewCbor(make([]byte, 0, 1024)) cbritem := config.NewCbor(make([]byte, 0, 1024)) olditem := config.NewCbor(make([]byte, 0, 1024)) config.NewJson([]byte(`[]`)).Tocbor(cbr1) fmt.Println("start with `[]`") ptr := config.NewJsonpointer("") config.NewValue(10.0).Tocbor(cbritem.Reset(nil)) cbr1.Append(ptr, cbritem, cbr2) fmt.Printf("after appending 10 %v\n", cbr2.Tovalue()) cbr1.Reset(nil) ptr = config.NewJsonpointer("") config.NewValue(20.0).Tocbor(cbritem.Reset(nil)) cbr2.Prepend(ptr, cbritem, cbr1) fmt.Printf("after prepending 20 %v\n", cbr1.Tovalue()) cbr2.Reset(nil) ptr = config.NewJsonpointer("/1") config.NewValue(30.0).Tocbor(cbritem.Reset(nil)) cbr1.Set(ptr, cbritem, cbr2, olditem) fmsg := "after setting 30 to second item %v old value %v\n" fmt.Printf(fmsg, cbr2.Tovalue(), olditem.Tovalue()) cbr1.Reset(nil) ptr = config.NewJsonpointer("/1") cbr2.Get(ptr, cbritem.Reset(nil)) fmt.Printf("get second item %v\n", cbritem.Tovalue()) ptr = config.NewJsonpointer("/0") cbr2.Delete(ptr, cbr1, cbritem.Reset(nil)) fmsg = "after deleting first item %v, deleted value %v\n" fmt.Printf(fmsg, cbr1.Tovalue(), cbritem.Tovalue()) cbr2.Reset(nil)
Output: start with `[]` after appending 10 [10] after prepending 20 [20 10] after setting 30 to second item [20 30] old value 10 get second item 30 after deleting first item [30], deleted value 20
func (*Cbor) Delete ¶
func (cbr *Cbor) Delete(jptr *Jsonpointer, newdoc, deleted *Cbor) *Cbor
Delete field or nested field specified by json-pointer.
func (*Cbor) EncodeBytechunks ¶
EncodeBytechunks to encode several chunks of bytes as an indefinite-sequence of byte-blocks.
func (*Cbor) EncodeMapslice ¶
EncodeMapslice to encode key,value pairs into cbor buffer. Whether to encode them as indefinite-sequence of pairs, or as length prefixed pairs is decided by config.ContainerEncoding.
func (*Cbor) EncodeSimpletype ¶
EncodeSimpletype to encode simple type into cbor buffer. Code points 0..19 and 32..255 are un-assigned.
func (*Cbor) EncodeSmallint ¶
EncodeSmallint to encode tiny integers between -23..+23 into cbor buffer.
func (*Cbor) EncodeTextchunks ¶
EncodeTextchunks to encode several chunks of text as an indefinite-sequence of byte-blocks.
func (*Cbor) Get ¶
func (cbr *Cbor) Get(jptr *Jsonpointer, item *Cbor) *Cbor
Get field or nested field specified by json-pointer.
func (*Cbor) Prepend ¶
func (cbr *Cbor) Prepend(jptr *Jsonpointer, item, newdoc *Cbor) *Cbor
Prepend item to the beginning of an array field specified by json-pointer.
func (*Cbor) Reset ¶
Reset overwrite buffer with data, or if data is nil, reset buffer to zero-length.
func (*Cbor) Set ¶
func (cbr *Cbor) Set(jptr *Jsonpointer, item, newdoc, old *Cbor) *Cbor
Set field or nested field specified by json-pointer.
type CborIndefinite ¶
type CborIndefinite byte
CborIndefinite code, {cborType2,Type3,Type4,Type5}/cborIndefiniteLength
type CborTagEpoch ¶
type CborTagEpoch int64
CborTagEpoch codepoint-1, followed by int64 of seconds since 1970-01-01T00:00Z in UTC time.
type CborTagEpochMicro ¶
type CborTagEpochMicro float64
CborTagEpochMicro codepoint-1, followed by float64 of seconds/us since 1970-01-01T00:00Z in UTC time.
type CborTagFloat ¶
type CborTagFloat [2]int64
CborTagFloat codepoint-5, followed by [2]int64{e,m} => m*(2**e).
type CborTagFraction ¶
type CborTagFraction [2]int64
CborTagFraction codepoint-4, followed by [2]int64{e,m} => m*(10**e).
type CborTagPrefix ¶
type CborTagPrefix []byte
CborTagPrefix codepoint-5579, followed by byte-string.
type CborUndefined ¶
type CborUndefined byte
CborUndefined simple type, cborType7/cborSimpleUndefined
type Collate ¶
type Collate struct {
// contains filtered or unexported fields
}
Collate abstraction for value encoded into binary-collation.
Example ¶
config := NewDefaultConfig() cbr := config.NewCbor(make([]byte, 0, 1024)) jsn := config.NewJson(make([]byte, 0, 1024)) clt := config.NewCollate(make([]byte, 0, 1024)) config.NewValue([]interface{}{10, 20, 100}).Tocollate(clt) fmt.Printf("json : %q\n", clt.Tojson(jsn).Bytes()) fmt.Printf("cbor : %q\n", clt.Tocbor(cbr).Bytes()) fmt.Printf("value: %v\n", clt.Tovalue())
Output: json : "[1e+01,2e+01,1e+02]" cbor : "\x9f\xfb@$\x00\x00\x00\x00\x00\x00\xfb@4\x00\x00\x00\x00\x00\x00\xfb@Y\x00\x00\x00\x00\x00\x00\xff" value: [10 20 100]
func (*Collate) Reset ¶
Reset overwrite buffer with data, or if data is nil, reset buffer to zero-length.
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config is the root object to access all transformations and APIs exported by this package. Before calling any of the config-methods, make sure to initialize them with desired settings.
NOTE: Config objects are immutable.
Example ¶
config := NewDefaultConfig() // override default configuration options. // IMPORTANT: config objects are immutable, so assign back // the new object returned by each of the settings method. config = config.SetContainerEncoding(LengthPrefix) config = config.SetJptrlen(1024).SetMaxkeys(10000) config = config.SetNumberKind(FloatNumber).SetSpaceKind(AnsiSpace) config = config.SortbyArrayLen(true).SortbyPropertyLen(true) config = config.UseMissing(false) fmt.Println(config)
Output: nk:FloatNumber, ws:AnsiSpace, ct:LengthPrefix, arrayLenPrefix:true, propertyLenPrefix:true, doMissing:false
func NewDefaultConfig ¶
func NewDefaultConfig() *Config
NewDefaultConfig return a new configuration with default settings:
+FloatNumber +Stream +UnicodeSpace -strict +doMissing -arrayLenPrefix +propertyLenPrefix MaxJsonpointerLen MaxKeys MaxStringLen MaxCollateLen
Several methods are available to change configuration parameters.
func (*Config) NewCbor ¶
NewCbor factory to create a new Cbor instance. If buffer is nil, a new buffer of 128 byte capacity will be allocated. Cbor object can be re-used after a Reset() call.
func (*Config) NewCollate ¶
NewCollate factor to create a new Collate instance. If buffer is nil, a new buffer of 128 byte capacity will be allocated. Collate object can be re-used after a Reset() call.
func (*Config) NewJson ¶
NewJson factory to create a new Json instance. If buffer is nil, a new buffer of 128 byte capacity will be allocated. Json object can be re-used after a Reset() call.
func (*Config) NewJsonpointer ¶
func (config *Config) NewJsonpointer(path string) *Jsonpointer
NewJsonpointer create a instance of Jsonpointer.
func (*Config) NewValue ¶
NewValue factory to create a new Value instance. Value instances are immutable, and can be used and re-used any number of times.
func (Config) ResetPools ¶
ResetPools configure a new set of pools with specified size, instead of using the default size: MaxStringLen, MaxKeys, MaxCollateLen, and, MaxJsonpointerLen.
strlen - maximum length of string value inside JSON document numkeys - maximum number of keys that a property object can have itemlen - maximum length of collated value. ptrlen - maximum possible length of json-pointer.
func (Config) SetContainerEncoding ¶
func (config Config) SetContainerEncoding(ct ContainerEncoding) *Config
SetContainerEncoding configure to encode / decode cbor arrays and maps.
func (Config) SetJptrlen ¶
SetJptrlen will set the maximum size for jsonpointer path.
func (Config) SetMaxkeys ¶
SetMaxkeys configure to set the maximum number of keys allowed in property item.
func (Config) SetNumberKind ¶
func (config Config) SetNumberKind(nk NumberKind) *Config
SetNumberKind configure to interpret number values.
func (Config) SetSpaceKind ¶
SetSpaceKind setting to interpret whitespaces in json text.
func (Config) SetStrict ¶
SetStrict setting to enforce strict transforms to and from JSON. If set to true,
a. IntNumber configuration float numbers in JSON text still are parsed. b. Use golang stdlib encoding/json for transforming strings to JSON.
func (Config) SetTextCollator ¶
SetTextCollator for string type. If collator is not set, strings will be treated as byte-array and compared as such.
func (Config) SortbyArrayLen ¶
SortbyArrayLen setting to sort array of smaller-size before larger ones.
func (Config) SortbyPropertyLen ¶
SortbyPropertyLen setting to sort properties of smaller size before larger ones.
func (Config) UseMissing ¶
UseMissing setting to use TypeMissing collation.
type ContainerEncoding ¶
type ContainerEncoding byte
ContainerEncoding method to encode arrays and maps into cbor.
const ( // LengthPrefix to encode number of items in the collection type. LengthPrefix ContainerEncoding = iota + 1 // Stream to encode collection types as indefinite sequence of items. Stream )
func (ContainerEncoding) String ¶
func (ct ContainerEncoding) String() string
type Json ¶
type Json struct {
// contains filtered or unexported fields
}
Json abstraction for value encoded as json text.
Example ¶
config := NewDefaultConfig() cbr := config.NewCbor(make([]byte, 0, 1024)) jsn := config.NewJson(make([]byte, 0, 1024)) clt := config.NewCollate(make([]byte, 0, 1024)) config.NewValue([]interface{}{10, 20, 100}).Tojson(jsn) fmt.Printf("collate : %q\n", jsn.Tocollate(clt).Bytes()) fmt.Printf("cbor : %q\n", jsn.Tocbor(cbr).Bytes()) _, value := jsn.Tovalue() fmt.Printf("value: %v\n", value)
Output: collate : "nP>>21-\x00P>>22-\x00P>>31-\x00\x00" cbor : "\x9f\xfb@$\x00\x00\x00\x00\x00\x00\xfb@4\x00\x00\x00\x00\x00\x00\xfb@Y\x00\x00\x00\x00\x00\x00\xff" value: [10 20 100]
func (*Json) Reset ¶
Reset overwrite buffer with data, or if data is nil, reset buffer to zero-length.
type Jsonpointer ¶
type Jsonpointer struct {
// contains filtered or unexported fields
}
Jsonpointer abstracts rfc-6901 into a type. allows ~0 and ~1 escapes, property lookup by specifying the key, and array lookup by specifying the index. Also allows empty "" pointer and empty key "/".
func (*Jsonpointer) ResetPath ¶
func (jptr *Jsonpointer) ResetPath(path string) *Jsonpointer
ResetPath to reuse the Jsonpointer object for a new path.
func (*Jsonpointer) ResetSegments ¶
func (jptr *Jsonpointer) ResetSegments(segments []string) *Jsonpointer
ResetSegments variant of ResetPath to reconstruct the path from segments.
func (*Jsonpointer) Segments ¶
func (jptr *Jsonpointer) Segments() [][]byte
Segments return path segments, segments in a path are separated by "/"
type Missing ¶
type Missing string
Missing denotes a special type for an item that evaluates to _nothing_.
type NumberKind ¶
type NumberKind byte
NumberKind how to treat numbers.
const ( // FloatNumber to treat number as float64. FloatNumber NumberKind = iota + 1 // SmartNumber to treat number as either integer or fall back to float64. SmartNumber )
func (NumberKind) String ¶
func (nk NumberKind) String() string
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value abstractions for golang-native value.
func (*Value) Append ¶
func (val *Value) Append(jptr *Jsonpointer, item interface{}) interface{}
Append item to end of an array pointed by json-pointer. returns `newval`, is guaranteed to be updated,
val := NewValue([]interface{}{"hello", "world"}) newval, _ = val.Append("", "welcome")
func (*Value) Delete ¶
func (val *Value) Delete(jptr *Jsonpointer) (newval, deleted interface{})
Delete field or nested field specified by json pointer. While `newval` is guaranteed to be updated, `val` _may_ not be. Suggested usage,
val := NewValue([]interface{}{"hello", "world"}) newval, _ = val.Delete("/1")
func (*Value) Get ¶
func (val *Value) Get(jptr *Jsonpointer) (item interface{})
Get field or nested field specified by json pointer.
func (*Value) ListPointers ¶
ListPointers all possible pointers in value.
func (*Value) Prepend ¶
func (val *Value) Prepend(jptr *Jsonpointer, item interface{}) interface{}
Prepend an item to the beginning of an array. returns `newval`, is guaranteed to be updated,
val := NewValue([]interface{}{"hello", "world"}) newval, _ = val.Append("", "welcome")
func (*Value) Set ¶
func (val *Value) Set(jptr *Jsonpointer, item interface{}) (newval, oldval interface{})
Set field or nested field specified by json pointer. While `newval` is guaranteed to contain the `item`, `val` _may_ not be. Suggested usage,
val := config.NewValue([]interface{}{"hello"}) newval, _ = val.Set("/-", "world")
Source Files ¶
- buffpool.go
- cbor.go
- cbor_collate.go
- cbor_json.go
- cbor_value.go
- clone_cbor.go
- collate.go
- collate_cbor.go
- collate_json.go
- collate_number.go
- collate_string.go
- collate_value.go
- config.go
- doc.go
- jptr.go
- json.go
- json_cbor.go
- json_collate.go
- json_scanner.go
- json_string.go
- json_value.go
- keyspool.go
- kvpool.go
- lookup_cbor.go
- lookup_value.go
- util.go
- value.go
- value_cbor.go
- value_collate.go
- value_json.go