Documentation ¶
Overview ¶
Package jsonvalue is for JSON parsing and setting. It is used in situations those Go structures cannot achieve, or "map[string]interface{}" could not do properbally.
As a quick start:
v := jsonvalue.NewObject() v.SetString("Hello, JSON").At("someObject", "someObject", "someObject", "message") // automatically create sub objects fmt.Println(v.MustMarshalString()) // marshal to string type. Use MustMarshal if you want []byte instead. // Output: // {"someObject":{"someObject":{"someObject":{"message":"Hello, JSON!"}}}
If you want to parse raw JSON data, use Unmarshal()
raw := []byte(`{"message":"hello, world"}`) v, err := jsonvalue.Unmarshal(raw) s, _ := v.GetString("message") fmt.Println(s) // Output: // hello, world
jsonvalue 包用于 JSON 的解析(反序列化)和编码(序列化)。通常情况下我们用 struct 来处理结构化的 JSON,但是有时候使用 struct 不方便或者是功能不足的时候, go 一般而言使用的是 "map[string]interface{}",但是后者也有很多不方便的地方。本包即是用于替代这些不方便的情况的。
快速上手:
v := jsonvalue.NewObject() v.SetString("Hello, JSON").At("someObject", "someObject", "someObject", "message") // 自动创建子成员 fmt.Println(v.MustMarshalString()) // 序列化为 string 类型,如果你要 []byte 类型,则使用 MustMarshal 函数。 // 输出: // {"someObject":{"someObject":{"someObject":{"message":"Hello, JSON!"}}}
如果要反序列化原始的 JSON 文本,则使用 Unmarshal():
raw := []byte(`{"message":"hello, world"}`) v, err := jsonvalue.Unmarshal(raw) s, _ := v.GetString("message") fmt.Println(s) // 输出: // hello, world
Index ¶
- Constants
- func DefaultStringSequence(parent *ParentInfo, key1, key2 string, v1, v2 *V) bool
- func ResetDefaultMarshalOptions()
- func SetDefaultMarshalOptions(opts ...Option)
- type Append
- type ArrayIterdeprecated
- type ArrayLessFunc
- type Caseless
- type Error
- type FloatInfHandleType
- type FloatNaNHandleType
- type Insert
- type Key
- type KeyPath
- type M
- type MarshalLessFunc
- type ObjectIterdeprecated
- type Optdeprecated
- func CombineOptions(opts []Option) *Optdeprecated
- type Option
- func OptDefaultStringSequence() Option
- func OptEscapeHTML(on bool) Option
- func OptEscapeSlash(on bool) Option
- func OptFloatInfToFloat(f float64) Option
- func OptFloatInfToNull() Option
- func OptFloatInfToString(positiveInf, negativeInf string) Option
- func OptFloatInfToStringInf() Option
- func OptFloatNaNToFloat(f float64) Option
- func OptFloatNaNToNull() Option
- func OptFloatNaNToString(s string) Option
- func OptFloatNaNToStringNaN() Option
- func OptKeySequence(seq []string) Option
- func OptKeySequenceWithLessFunc(f MarshalLessFunc) Option
- func OptOmitNull(b bool) Option
- func OptUTF8() Option
- type ParentInfo
- type Set
- type V
- func Import(src interface{}) (*V, error)
- func MustUnmarshal(b []byte) *V
- func MustUnmarshalNoCopy(b []byte) *V
- func MustUnmarshalString(s string) *V
- func NewArray() *V
- func NewBool(b bool) *V
- func NewBytes(b []byte) *V
- func NewFloat32(f float32) *V
- func NewFloat32f(f float32, format byte, prec int) *V
- func NewFloat64(f float64) *V
- func NewFloat64f(f float64, format byte, prec int) *V
- func NewInt(i int) *V
- func NewInt32(i int32) *V
- func NewInt64(i int64) *V
- func NewNull() *V
- func NewObject(keyValues ...M) *V
- func NewString(s string) *V
- func NewUint(u uint) *V
- func NewUint32(u uint32) *V
- func NewUint64(u uint64) *V
- func Unmarshal(b []byte) (ret *V, err error)
- func UnmarshalNoCopy(b []byte) (ret *V, err error)
- func UnmarshalString(s string) (*V, error)
- func (v *V) Append(child *V) *Append
- func (v *V) AppendArray() *Append
- func (v *V) AppendBool(b bool) *Append
- func (v *V) AppendBytes(b []byte) *Append
- func (v *V) AppendFloat32(f float32) *Append
- func (v *V) AppendFloat64(f float64) *Append
- func (v *V) AppendInt(i int) *Append
- func (v *V) AppendInt32(i int32) *Append
- func (v *V) AppendInt64(i int64) *Append
- func (v *V) AppendNull() *Append
- func (v *V) AppendObject() *Append
- func (v *V) AppendString(s string) *Append
- func (v *V) AppendUint(u uint) *Append
- func (v *V) AppendUint32(u uint32) *Append
- func (v *V) AppendUint64(u uint64) *Append
- func (v *V) Bool() bool
- func (v *V) Bytes() []byte
- func (v *V) Caseless() Caseless
- func (v *V) Delete(firstParam interface{}, otherParams ...interface{}) error
- func (v *V) Export(dst interface{}) error
- func (v *V) Float32() float32
- func (v *V) Float64() float64
- func (v *V) ForRangeArr() []*V
- func (v *V) ForRangeObj() map[string]*V
- func (v *V) Get(firstParam interface{}, otherParams ...interface{}) (*V, error)
- func (v *V) GetArray(firstParam interface{}, otherParams ...interface{}) (*V, error)
- func (v *V) GetBool(firstParam interface{}, otherParams ...interface{}) (bool, error)
- func (v *V) GetBytes(firstParam interface{}, otherParams ...interface{}) ([]byte, error)
- func (v *V) GetFloat32(firstParam interface{}, otherParams ...interface{}) (float32, error)
- func (v *V) GetFloat64(firstParam interface{}, otherParams ...interface{}) (float64, error)
- func (v *V) GetInt(firstParam interface{}, otherParams ...interface{}) (int, error)
- func (v *V) GetInt32(firstParam interface{}, otherParams ...interface{}) (int32, error)
- func (v *V) GetInt64(firstParam interface{}, otherParams ...interface{}) (int64, error)
- func (v *V) GetNull(firstParam interface{}, otherParams ...interface{}) error
- func (v *V) GetObject(firstParam interface{}, otherParams ...interface{}) (*V, error)
- func (v *V) GetString(firstParam interface{}, otherParams ...interface{}) (string, error)
- func (v *V) GetUint(firstParam interface{}, otherParams ...interface{}) (uint, error)
- func (v *V) GetUint32(firstParam interface{}, otherParams ...interface{}) (uint32, error)
- func (v *V) GetUint64(firstParam interface{}, otherParams ...interface{}) (uint64, error)
- func (v *V) GreaterThanInt64Max() bool
- func (v *V) Insert(child *V) *Insert
- func (v *V) InsertArray() *Insert
- func (v *V) InsertBool(b bool) *Insert
- func (v *V) InsertFloat32(f float32) *Insert
- func (v *V) InsertFloat64(f float64) *Insert
- func (v *V) InsertInt(i int) *Insert
- func (v *V) InsertInt32(i int32) *Insert
- func (v *V) InsertInt64(i int64) *Insert
- func (v *V) InsertNull() *Insert
- func (v *V) InsertObject() *Insert
- func (v *V) InsertString(s string) *Insert
- func (v *V) InsertUint(u uint) *Insert
- func (v *V) InsertUint32(u uint32) *Insert
- func (v *V) InsertUint64(u uint64) *Insert
- func (v *V) Int() int
- func (v *V) Int32() int32
- func (v *V) Int64() int64
- func (v *V) IsArray() bool
- func (v *V) IsBoolean() bool
- func (v *V) IsFloat() bool
- func (v *V) IsInteger() bool
- func (v *V) IsNegative() bool
- func (v *V) IsNull() bool
- func (v *V) IsNumber() bool
- func (v *V) IsObject() bool
- func (v *V) IsPositive() bool
- func (v *V) IsString() bool
- func (v *V) IterArray() <-chan *ArrayIterdeprecated
- func (v *V) IterObjects() <-chan *ObjectIterdeprecated
- func (v *V) Len() int
- func (v *V) Marshal(opts ...Option) (b []byte, err error)
- func (v *V) MarshalString(opts ...Option) (s string, err error)
- func (v *V) MustGet(firstParam interface{}, otherParams ...interface{}) *V
- func (v *V) MustMarshal(opts ...Option) []byte
- func (v *V) MustMarshalString(opt ...Option) string
- func (v *V) RangeArray(callback func(i int, v *V) bool)
- func (v *V) RangeObjects(callback func(k string, v *V) bool)
- func (v *V) Set(child *V) *Set
- func (v *V) SetArray() *Set
- func (v *V) SetBool(b bool) *Set
- func (v *V) SetBytes(b []byte) *Set
- func (v *V) SetFloat32(f float32) *Set
- func (v *V) SetFloat64(f float64) *Set
- func (v *V) SetInt(i int) *Set
- func (v *V) SetInt32(i int32) *Set
- func (v *V) SetInt64(i int64) *Set
- func (v *V) SetNull() *Set
- func (v *V) SetObject() *Set
- func (v *V) SetString(s string) *Set
- func (v *V) SetUint(u uint) *Set
- func (v *V) SetUint32(u uint32) *Set
- func (v *V) SetUint64(u uint64) *Set
- func (v *V) SortArray(lessFunc ArrayLessFunc)
- func (v *V) String() string
- func (v *V) Uint() uint
- func (v *V) Uint32() uint32
- func (v *V) Uint64() uint64
- func (v *V) ValueType() ValueType
- type ValueType
Examples ¶
Constants ¶
const ( // ErrNilParameter identifies input paremeter is nil // // ErrNilParameter 表示参数为空 ErrNilParameter = Error("nil parameter") // ErrValueUninitialized identifies that a V object is not initialized // // ErrValueUninitialized 表示当前的 jsonvalue 实例未初始化 ErrValueUninitialized = Error("jsonvalue instance is not initialized") // ErrRawBytesUnrecignized identifies all unexpected raw bytes // // ErrRawBytesUnrecignized 表示无法识别的序列文本 ErrRawBytesUnrecignized = Error("unrecognized raw text") // ErrNotValidNumberValue shows that a value starts with number or '-' is not eventually a number value // // ErrNotValidNumberValue 表示当前值不是一个合法的数值值 ErrNotValidNumberValue = Error("not a valid number value") // ErrNotValidBoolValue shows that a value starts with 't' or 'f' is not eventually a bool value // // ErrNotValidBoolValue 表示当前值不是一个合法的布尔值 ErrNotValidBoolValue = Error("not a valid bool value") // ErrNotValidNulllValue shows that a value starts with 'n' is not eventually a bool value // // ErrNotValidNulllValue 表示当前不是一个 null 值类型的 JSON ErrNotValidNulllValue = Error("not a valid null value") // ErrOutOfRange identifies that given position for a JSON array is out of range // // ErrOutOfRange 表示请求数组成员超出数组范围 ErrOutOfRange = Error("out of range") // ErrNotFound shows that given target is not found in Delete() // // ErrNotFound 表示目标无法找到 ErrNotFound = Error("target not found") // ErrTypeNotMatch shows that value type is not same as GetXxx() // // ErrTypeNotMatch 表示指定的对象不匹配 ErrTypeNotMatch = Error("not match given type") // ErrParseNumberFromString shows the error when parsing number from string // // ErrParseNumberFromString 表示从 string 类型的 value 中读取数字失败 ErrParseNumberFromString = Error("failed to parse number from string") // ErrNotArrayValue shows that operation target value is not an array // // ErrNotArrayValue 表示当前不是一个数组类型 JSON ErrNotArrayValue = Error("not an array typed value") // ErrNotObjectValue shows that operation target value is not an valie object // // ErrNotObjectValue 表示当前不是一个合法的对象类型 JSON ErrNotObjectValue = Error("not an object typed value") // ErrIllegalString shows that it is not a legal JSON string typed value // // ErrIllegalString 表示字符串不合法 ErrIllegalString = Error("illegal string") // ErrUnsupportedFloat shows that float value is not supported, like +Inf, -Inf and NaN. // // ErrUnsupportedFloat 表示 float64 是一个不支持的数值,如 +Inf, -Inf 和 NaN ErrUnsupportedFloat = Error("unsupported float value") // ErrUnsupportedFloatInOpt shows that float value in option is not supported, like +Inf, -Inf and NaN. // // ErrUnsupportedFloat 表示配置中的 float64 是一个不支持的数值,如 +Inf, -Inf 和 NaN ErrUnsupportedFloatInOpt = Error("unsupported float value in option") )
Variables ¶
This section is empty.
Functions ¶
func DefaultStringSequence ¶
func DefaultStringSequence(parent *ParentInfo, key1, key2 string, v1, v2 *V) bool
DefaultStringSequence simply use strings.Compare() to define the sequence of various key-value pairs of an object value. This function is used in Opt.MarshalLessFunc.
DefaultStringSequence 使用 strings.Compare() 函数来判断键值对的顺序。用于 Opt.MarshalLessFunc。
func ResetDefaultMarshalOptions ¶
func ResetDefaultMarshalOptions()
ResetDefaultMarshalOptions reset default marshaling options to system default.
ResetDefaultMarshalOptions 重设序列化时的默认选项为系统最原始的版本。
func SetDefaultMarshalOptions ¶
func SetDefaultMarshalOptions(opts ...Option)
SetDefaultMarshalOptions set default option for marshaling. It is quite useful to invoke this function once in certern init funciton. Or you can invoke it after main entry. It is goroutine-safe.
Please keep in mind that it takes effect globally and affects ALL marshaling behaviors in the future until the process ends. Please ensure that these options are acceptable for ALL future marshaling.
However, you can still add additional options in later marshaling.
SetDefaultMarshalOptions 设置序列化时的默认参数。使用方可以在 init 函数阶段,或者是 main 函数启动后立刻调用该函数,以调整序列化时的默认行为。这个函数是协程安全的。
请记住,这个函数影响的是后续所有的序列化行为,请确保这个配置对后续的其他操作是可行的。
当然,你也可以在后续的操作中,基于原先配置的默认选项基础上,添加其他附加选项。
Types ¶
type Append ¶
type Append struct {
// contains filtered or unexported fields
}
Append type is for InTheEnd() or InTheBeginning() function. Please refer to related functions.
Shoud ONLY be generated by V.Append() function ¶
Append 类型是用于 InTheEnd() 和 InTheBeginning() 函数的。使用者可以不用关注这个类型。并且这个类型只应当由 V.Append() 产生。
func (*Append) InTheBeginning ¶
InTheBeginning completes the following operation of Append().
InTheBeginning 函数将 Append 函数指定的 JSON 值,添加到参数指定的数组的最前端
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `{"obj":{"arr":[1,2,3,4,5]}}` v, err := jsonvalue.UnmarshalString(s) if err != nil { panic(err) } // append a zero in the bebinning of v.obj.arr v.AppendInt(0).InTheBeginning("obj", "arr") s = v.MustMarshalString() fmt.Println(s) }
Output: {"obj":{"arr":[0,1,2,3,4,5]}}
func (*Append) InTheEnd ¶
InTheEnd completes the following operation of Append().
InTheEnd 函数将 Append 函数指定的 JSON 值,添加到参数指定的数组的最后面
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `{"obj":{"arr":[1,2,3,4,5]}}` v, _ := jsonvalue.UnmarshalString(s) // append a zero in the end of v.obj.arr v.AppendInt(0).InTheEnd("obj", "arr") s = v.MustMarshalString() fmt.Println(s) }
Output: {"obj":{"arr":[1,2,3,4,5,0]}}
type ArrayLessFunc ¶
ArrayLessFunc is used in SortArray(), identifying which member is ahead.
ArrayLessFunc 用于 SortArray() 函数中,指定两个成员谁在前面。
type Caseless ¶
type Caseless interface { Get(firstParam interface{}, otherParams ...interface{}) (*V, error) MustGet(firstParam interface{}, otherParams ...interface{}) *V GetBytes(firstParam interface{}, otherParams ...interface{}) ([]byte, error) GetString(firstParam interface{}, otherParams ...interface{}) (string, error) GetInt(firstParam interface{}, otherParams ...interface{}) (int, error) GetUint(firstParam interface{}, otherParams ...interface{}) (uint, error) GetInt64(firstParam interface{}, otherParams ...interface{}) (int64, error) GetUint64(firstParam interface{}, otherParams ...interface{}) (uint64, error) GetInt32(firstParam interface{}, otherParams ...interface{}) (int32, error) GetUint32(firstParam interface{}, otherParams ...interface{}) (uint32, error) GetFloat64(firstParam interface{}, otherParams ...interface{}) (float64, error) GetFloat32(firstParam interface{}, otherParams ...interface{}) (float32, error) GetBool(firstParam interface{}, otherParams ...interface{}) (bool, error) GetNull(firstParam interface{}, otherParams ...interface{}) error GetObject(firstParam interface{}, otherParams ...interface{}) (*V, error) GetArray(firstParam interface{}, otherParams ...interface{}) (*V, error) Delete(firstParam interface{}, otherParams ...interface{}) error }
Caseless is returned by Caseless(). operations of Caseless type are same as (*V).Get(), but are via caseless key.
Caseless 类型通过 Caseless() 函数返回。通过 Caseless 接口操作的所有操作均与 (*v).Get() 相同,但是对 key 进行读取的时候, 不区分大小写。
type Error ¶
type Error string
Error is equavilent to string and used to create some error constants in this package. Error constants: http://godoc.org/github.com/Andrew-M-C/go.jsonvalue/#pkg-constants
type FloatInfHandleType ¶
type FloatInfHandleType uint8
const ( // FloatInfTreatAsError indicates that error will be returned when a float number is Inf or -Inf when marshaling. // // FloatInfTreatAsError 表示当 marshal 遇到 Inf 或 -Inf 时,返回错误。这是默认选项。 FloatInfTreatAsError FloatInfHandleType = 0 // FloatInfConvertToFloat indicates that Inf and -Inf will be replaced as another float number when marshaling. // This option works with option FloatInfToFloat. // // FloatInfConvertToFloat 表示当 marshal 遇到 Inf 或 -Inf 时,将值置为另一个数。搭配 FloatInfToFloat 选项使用。 FloatInfConvertToFloat FloatInfHandleType = 1 // FloatInfNull indicates that Inf or -Inf key-value pair will be set as null when marshaling. // // FloatInfNull 表示当 marshal 遇到 Inf 和 -Inf 时,则将值设置为 null FloatInfNull FloatInfHandleType = 2 // FloatInfConvertToString indicates that Inf anf -Inf will be replaced as a string when marshaling. This option // works with option FloatInfPositiveToString and FloatInfNegativeToString. // // FloatInfConvertToString 表示当 marshal 遇到 Inf 和 -Inf 时,将值设置为一个字符串。搭配 FloatInfPositiveToString // FloatInfNegativeToString 选项使用。 FloatInfConvertToString FloatInfHandleType = 3 )
type FloatNaNHandleType ¶
type FloatNaNHandleType uint8
const ( // FloatNaNTreatAsError indicates that error will be returned when a float number is NaN when marshaling. // // FloatNaNTreatAsError 表示当 marshal 遇到 NaN 时,返回错误。这是默认选项。 FloatNaNTreatAsError FloatNaNHandleType = 0 // FloatNaNConvertToFloat indicates that NaN will be replaced as another float number when marshaling. This option // works with option FloatNaNToFloat. // // FloatNaNConvertToFloat 表示当 marshal 遇到 NaN 时,将值置为另一个数。搭配 FloatNaNToFloat 选项使用。 FloatNaNConvertToFloat FloatNaNHandleType = 1 // FloatNaNNull indicates that NaN key-value pair will be set as null when marshaling. // // FloatNaNNull 表示当 marshal 遇到 NaN 时,则将值设置为 null FloatNaNNull FloatNaNHandleType = 2 // FloatNaNConvertToString indicates that NaN will be replaced as a string when marshaling. This option // works with option FloatNaNToString. // // FloatNaNConvertToString 表示当 marshal 遇到 NaN 时,将值设置为一个字符串。搭配 FloatNaNToString 选项使用。 FloatNaNConvertToString FloatNaNHandleType = 3 )
type Insert ¶
type Insert struct {
// contains filtered or unexported fields
}
Insert type is for After() and Before() function. Please refer for realated function.
Should be generated ONLY BY V.Insert function!
Insert 类型适用于 After() 和 Before() 函数。请参见相关函数。请注意:该类型仅应由 V.Insert 函数生成!
func (*Insert) After ¶
After completes the following operation of Insert(). It inserts value AFTER specified position.
The last parameter identifies the postion where a new JSON is inserted after, it should ba an interger, no matter signed or unsigned. If the position is zero or positive interger, it tells the index of an array. If the position is negative, it tells the backward index of an array.
For example, 0 represents the first, and -2 represents the second last.
After 结束并完成 Insert() 函数的后续插入操作,表示插入到指定位置的前面。
在 Before 函数的最后一个参数指定了被插入的 JSON 数组的位置,这个参数应当是一个整型(有无符号类型均可)。 如果这个值等于0或者正整数,那么它指定的是在 JSON 数组中的位置(从0开始)。如果这个值是负数,那么它指定的是 JSON 数组中从最后一个位置开始算起的位置。
举例说明:0 表示第一个位置,而 -2 表示倒数第二个位置。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `{"obj":{"arr":["hello","world"]}}` v, _ := jsonvalue.UnmarshalString(s) // insert a word in the middle, which is after the first word of the array v.InsertString("my").After("obj", "arr", 0) fmt.Println(v.MustMarshalString()) }
Output: {"obj":{"arr":["hello","my","world"]}}
func (*Insert) Before ¶
Before completes the following operation of Insert(). It inserts value BEFORE specified position.
The last parameter identifies the postion where a new JSON is inserted after, it should ba an interger, no matter signed or unsigned. If the position is zero or positive interger, it tells the index of an array. If the position is negative, it tells the backward index of an array.
For example, 0 represents the first, and -2 represents the second last.
Before 结束并完成 Insert() 函数的后续插入操作,表示插入到指定位置的后面。
在 Before 函数的最后一个参数指定了被插入的 JSON 数组的位置,这个参数应当是一个整型(有无符号类型均可)。 如果这个值等于0或者正整数,那么它指定的是在 JSON 数组中的位置(从0开始)。如果这个值是负数,那么它指定的是 JSON 数组中从最后一个位置开始算起的位置。
举例说明:0 表示第一个位置,而 -2 表示倒数第二个位置。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `{"obj":{"arr":["hello","world"]}}` v, _ := jsonvalue.UnmarshalString(s) // insert a word in the middle, which is before the second word of the array v.InsertString("my").Before("obj", "arr", 1) fmt.Println(v.MustMarshalString()) }
Output: {"obj":{"arr":["hello","my","world"]}}
type Key ¶
type Key struct {
// contains filtered or unexported fields
}
Key is the element of KeyPath
Key 是 KeyPath 类型的成员
func (*Key) IsInt ¶
IsInt tells if current key is a integer, which indicates a child of an array
IsInt 判断当前的键是不是一个整型类型,如果是的话,那么它是一个 array JSON 的子成员。
type KeyPath ¶
type KeyPath []*Key
KeyPath identifies a full path of keys of object in jsonvalue.
KeyPath 表示一个对象在指定 jsonvalue 中的完整的键路径。
type MarshalLessFunc ¶
type MarshalLessFunc func(nilableParent *ParentInfo, key1, key2 string, v1, v2 *V) bool
MarshalLessFunc is used in marshaling, for sorting marshaled data.
MarshalLessFunc 用于序列化,指定 object 类型的 JSON 的键值对顺序。
type ObjectIter
deprecated
type Opt
deprecated
type Opt struct { // OmitNull tells how to handle null json value. The default value is false. // If OmitNull is true, null value will be omitted when marshaling. // // OmitNull 表示是否忽略 JSON 中的 null 类型值。默认为 false. OmitNull bool // MarshalLessFunc is used to handle sequences of marshaling. Since object is // implemented by hash map, the sequence of keys is unexpectable. For situations // those need settled JSON key-value sequence, please use MarshalLessFunc. // // Note: Elements in an array value would NOT trigger this function as they are // already sorted. // // We provides a example DefaultStringSequence. It is quite useful when calculating // idempotence of a JSON text, as key-value sequences should be fixed. // // MarshalLessFunc 用于处理序列化 JSON 对象类型时,键值对的顺序。由于 object 类型是采用 go 原生的 map 类型,采用哈希算法实现, // 因此其键值对的顺序是不可控的。而为了提高效率,jsonvalue 的内部实现中并不会刻意保存键值对的顺序。如果有必要在序列化时固定键值对顺序的话, // 可以使用这个函数。 // // 注意:array 类型中键值对的顺序不受这个函数的影响 // // 此外,我们提供了一个例子: DefaultStringSequence。当需要计算 JSON 文本的幂等值时, // 由于需要不变的键值对顺序,因此这个函数是非常有用的。 MarshalLessFunc MarshalLessFunc // MarshalKeySequence is used to handle sequance of marshaling. This is much simpler // than MarshalLessFunc, just pass a string slice identifying key sequence. For keys // those are not in this slice, they would be appended in the end according to result // of Go string comparing. Therefore this parameter is useful for ensure idempotence. // // MarshalKeySequence 也用于处理序列化时的键值对顺序。与 MarshalLessFunc 不同,这个只需要用字符串切片的形式指定键的顺序即可, // 实现上更为简易和直观。对于那些不在指定切片中的键,那么将会统一放在结尾,并且按照 go 字符串对比的结果排序。也可以保证幂等。 MarshalKeySequence []string // FloatNaNHandleType tells what to deal with float NaN. // // FloatNaNHandleType 表示当处理 float 的时候,如果遇到了 NaN 的话,要如何处理。 FloatNaNHandleType FloatNaNHandleType // FloatNaNToString works with FloatNaNHandleType = FloatNaNConvertToString. It tells what string to replace // to with NaN. If not specified, NaN will be set as string "NaN". // // FloatNaNToString 搭配 FloatNaNHandleType = FloatNaNConvertToString 使用,表示将 NaN 映射为哪个字符串。 // 这个值如果不指定,则默认会被设置为字符串 "NaN" FloatNaNToString string // FloatNaNToFloat works with FloatNaNHandleType = FloatNaNConvertToFloat. It tells what float number will // be mapped to as for NaN. NaN, +Inf or -Inf are not allowed for this option. // // FloatNaNToFloat 搭配 FloatNaNHandleType = FloatNaNConvertToFloat 使用,表示将 NaN 映射为哪个 float64 值。 // 不允许指定为 NaN, +Inf 或 -Inf。如果不指定,则映射为 0 FloatNaNToFloat float64 // FloatInfHandleType tells what to deal with float +Inf and -Inf. // // FloatInfHandleType 表示当处理 float 的时候,如果遇到了 +Inf 和 -Inf 的话,要如何处理。 FloatInfHandleType FloatInfHandleType // FloatInfPositiveToString works with FloatInfHandleType = FloatInfConvertToFloat. It tells what float number will // be mapped to as for +Inf. If not specified, +Inf will be set as string "+Inf" // // FloatInfPositiveToString 搭配 FloatInfHandleType = FloatInfConvertToFloat 使用,表示将 NaN 映射为哪个字符串。 // 这个值如果不指定,则默认会被设置为字符串 "+Inf" FloatInfPositiveToString string // FloatInfNegativeToString works with FloatInfHandleType = FloatInfConvertToFloat. It tells what float number will // be mapped to as for -Inf. If not specified, -Inf will be set as string "-" + strings.TrimLeft(FloatInfPositiveToString, "+"). // // FloatInfNegativeToString 搭配 FloatInfHandleType = FloatInfConvertToFloat 使用,表示将 NaN 映射为哪个字符串。 // 这个值如果不指定,则默认会被设置为字符串 "-" + strings.TrimLeft(FloatInfPositiveToString, "+")。 FloatInfNegativeToString string // FloatInfToFloat works with FloatInfHandleType = FloatInfConvertToFloat. It tells what float numbers will be // mapped to as for +Inf. And -Inf will be specified as the negative value of this option. // +Inf or -Inf are not allowed for this option. // // FloatInfToFloat 搭配 FloatInfHandleType = FloatInfConvertToFloat 使用,表示将 +Inf 映射为哪个 float64 值。而 -Inf // 则会被映射为这个值的负数。 // 不允许指定为 NaN, +Inf 或 -Inf。如果不指定,则映射为 0 FloatInfToFloat float64 // contains filtered or unexported fields }
Deprecated: Opt is the option of jsonvalue in marshaling. This type is deprecated, please use OptXxxx() functions instead.
Opt 表示序列化当前 jsonvalue 类型时的参数。这个类型后续可能不再迭代新字段了,请改用 OptXxxx() 函数进行配置。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { raw := `{"null":null}` v, _ := jsonvalue.UnmarshalString(raw) s := v.MustMarshalString() fmt.Println(s) s = v.MustMarshalString(jsonvalue.OptOmitNull(true)) fmt.Println(s) }
Output: {"null":null} {}
func CombineOptions
deprecated
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option is used for additional options when marshaling. Can be either a Opt{} (not pointer to it) or other options generated by jsonvalue.OptXxxx() functions.
Option 表示用于序列化的额外选项。可以是一个 Opt{} 结构体值(而不是它的指针),或者是使用 jsonvalue.OptXxxx() 函数生成的选项。
func OptDefaultStringSequence ¶
func OptDefaultStringSequence() Option
OptDefaultStringSequence configures MarshalLessFunc field in Opt{} as jsonvalue.DefaultStringSequence, which is dictionary sequence.
OptDefaultStringSequence 配置 Opt{} 中的 MarshalLessFunc 字段为 jsonvalue.DefaultStringSequence,也就是字典序。
func OptEscapeHTML ¶
OptEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML. If not specified, HTML symbols above will be escaped by default.
OptEscapeHTML 指定部分 HTML 符号是否会被转义。相关的 HTML 符号为 &, <, > 三个。如无指定,则默认会被转义
func OptEscapeSlash ¶
OptEscapeSlash specifies whether we should escape slash (/) symbol. In JSON standard, this character should be escaped as '\/'. But non-escaping will not affect anything. If not specfied, slash will be escaped by default.
OptEscapeSlash 指定是否需要转移斜杠 (/) 符号。在 JSON 标准中这个符号是需要被转移为 '\/' 的,
但是不转义这个符号也不会带来什么问题。如无明确指定,如无指定,默认情况下,斜杠是会被转义的。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() v.SetString("https://google.com").At("google") defaultStr := v.MustMarshalString() escapeStr := v.MustMarshalString(jsonvalue.OptEscapeSlash(true)) nonEscape := v.MustMarshalString(jsonvalue.OptEscapeSlash(false)) fmt.Println("default -", defaultStr) fmt.Println("escape -", escapeStr) fmt.Println("non-esc -", nonEscape) }
Output: default - {"google":"https:\/\/google.com"} escape - {"google":"https:\/\/google.com"} non-esc - {"google":"https://google.com"}
func OptFloatInfToFloat ¶
OptFloatInfToFloat will replace a +Inf float value to specified f, while -f if the value is -Inf.
OptFloatInfToFloat 表示当遇到 +Inf 时,将其替换成另一个 float 值;如果是 -Inf,则会替换成其取负数。
func OptFloatInfToNull ¶
func OptFloatInfToNull() Option
OptFloatInfToNull will replace a float value to null if it is +/-Inf.
OptFloatInfToNull 表示当遇到 +/-Inf 时,将值替换成 null
func OptFloatInfToString ¶
OptFloatInfToString tells what string to replace when marshaling +Inf and -Inf numbers.
OptFloatInfToString 表示遇到 +/-Inf 时,将其替换成什么字符串。
func OptFloatInfToStringInf ¶
func OptFloatInfToStringInf() Option
OptFloatInfToStringInf will replace a +Inf value to string "+Inf", while -Inf to "-Inf"
OptFloatInfToStringInf 表示遇到 +/-Inf 时,相应地将其替换成字符串 "+Inf" 和 "-Inf"
func OptFloatNaNToFloat ¶
OptFloatNaNToFloat tells that when marshaling float NaN, replace it as another valid float number.
OptFloatNaNToFloat 指定当遇到 NaN 时,将值替换成一个有效的 float 值。
func OptFloatNaNToNull ¶
func OptFloatNaNToNull() Option
OptFloatNaNToNull will replace a float value to null if it is NaN.
OptFloatNaNToNull 表示当遇到 NaN 时,将值替换成 null
func OptFloatNaNToString ¶
OptFloatNaNToString will replace a float value to specified string if it is NaN. If empty string is given, will replace as "NaN".
OptFloatNaNToString 表示当遇到 NaN 时,将其替换成指定的字符串。如果指定空字符串,则替换成 "NaN"
func OptFloatNaNToStringNaN ¶
func OptFloatNaNToStringNaN() Option
OptFloatNaNToStringNaN will replace a float value to string "NaN" if it is NaN.
OptFloatNaNToStringNaN 表示遇到 NaN 时,将其替换成字符串 "NaN"
func OptKeySequence ¶
OptKeySequence configures MarshalKeySequence field in Opt{}.
OptKeySequence 配置 Opt{} 中的 MarshalKeySequence 字段。
func OptKeySequenceWithLessFunc ¶
func OptKeySequenceWithLessFunc(f MarshalLessFunc) Option
OptKeySequenceWithLessFunc configures MarshalLessFunc field in Opt{}, which defines key sequence when marshaling.
OptKeySequenceWithLessFunc 配置 Opt{} 中的 MarshalLessFunc 字段,配置序列化时的键顺序。
func OptOmitNull ¶
OptOmitNull configures OmitNull field in Opt{}, identifying whether null values should be omitted when marshaling.
OptOmitNull 配置 Opt{} 中的 OmitNull 字段,表示是否忽略 null 值。
func OptUTF8 ¶
func OptUTF8() Option
OptUTF8 specifies that all unicodes greater than 0x7F, will NOT be escaped by \uXXXX format but UTF-8.
OptUTF8 指定使用 UTF-8 编码。也就是说针对大于 0x7F 的 unicode 字符,将不会使用默认的 \uXXXX 格式进行编码,而是直接使用 UTF-8。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() v.SetString("🇺🇸🇨🇳🇷🇺🇬🇧🇫🇷").At("UN_leaderships") asciiString := v.MustMarshalString() utf8String := v.MustMarshalString(jsonvalue.OptUTF8()) fmt.Println("ASCII -", asciiString) fmt.Println("UTF-8 -", utf8String) }
Output: ASCII - {"UN_leaderships":"\uD83C\uDDFA\uD83C\uDDF8\uD83C\uDDE8\uD83C\uDDF3\uD83C\uDDF7\uD83C\uDDFA\uD83C\uDDEC\uD83C\uDDE7\uD83C\uDDEB\uD83C\uDDF7"} UTF-8 - {"UN_leaderships":"🇺🇸🇨🇳🇷🇺🇬🇧🇫🇷"}
type ParentInfo ¶
ParentInfo show informations of parent of a JSON value.
ParentInfo 表示一个 JSON 值的父节点信息。
type Set ¶
type Set struct {
// contains filtered or unexported fields
}
Set type is for At() only. Please refer to At() function.
This should be generated by V.Set functions ONLY.
Set 类型仅用于 At() 函数,请参见 At() 函数的说明。并且该类型只能使用 V.Set 函数生成。
func (*Set) At ¶
At completes the following operation of Set(). It defines posttion of value in Set() and return the new value set.
The usage of At() is perhaps the most important. This function will recursivly search for child value, and set the new value specified by Set() or SetXxx() series functions. Please unfold and read the following examples, they are important.
At 完成 Set() 函数的后续操作并设置相应的子成员。其参数指定了应该在哪个位置设置子成员,并且返回被设置的子成员对象。
该函数的用法恐怕是 jsonvalue 中最重要的内容了:该函数会按照给定的可变参数递归地一层一层查找 JSON 值的子成员,并且设置到指定的位置上。 设置的逻辑说明起来比较抽象,请打开以下的例子以了解,这非常重要。
Example ¶
For a simplest example:
这是最简单的例子:
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() // {} v.SetObject().At("obj") // {"obj":{}} v.SetString("Hello, world!").At("obj", "message") // {"obj":{"message":"Hello, world!"}} fmt.Println(v.MustMarshalString()) }
Output: {"obj":{"message":"Hello, world!"}}
Example (Another) ¶
Or you can make it even more simpler, as At() function will automatically create objects those do not exist
或者你还可以更加简洁,因为 At() 函数会自动创建在值链中所需要但未创建的对象
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() // {} v.SetString("Hello, world!").At("obj", "message") // {"obj":{"message":"Hello, world!"}} fmt.Println(v.MustMarshalString()) }
Output: {"obj":{"message":"Hello, world!"}}
Example (Another2) ¶
As for array, At() also works
对于数组类型,At() 也是能够自动生成的
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() // {} v.SetString("Hello, world!").At("arr", 0) // {"arr":[Hello, world!]} fmt.Println(v.MustMarshalString()) }
Output: {"arr":["Hello, world!"]}
Example (Another3) ¶
Auto-array-creating in At() function is actually a bit complicated. It fails when specifying an position that the array does not have yet. But with one exception: the index value is equal to the length of an array, in this case, a new value will be append to the end of the array. This is quite convient when setting array elements in a for-range block.
在 At() 自动创建数组的逻辑其实稍微有点复杂,需要解释一下。当调用方在参数中指定在某个尚未存在的数组中设置一个值的时候,那么 At() 指定的位置(position)数字, 应当为0,操作才能成功;而当数组已经存在,那么 At() 指定的位置数,要么在数组中已存在,要么正好等于数组的长度,当后者的情况下,会在数组的最后追加值。 这个特性在使用 for-range 块时会非常有用。
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() // {} _, err := v.SetString("Hello, world").At("arr", 1) // failed because there are no children of v.arr if err != nil { fmt.Println("got error:", err) } fmt.Println(v.MustMarshalString()) // as error occurred, the "arr" array would not be set integers := []int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100} for i, n := range integers { // this will succeed because i is equal to len(v.arr) every time v.SetInt(n).At("arr", i) } fmt.Println(v.MustMarshalString()) }
Output: got error: out of range {} {"arr":[10,20,30,40,50,60,70,80,90,100]}
Example (Another4) ¶
As for elements those in positions that the array already has, At() will REPLACE it.
正如上文所述,如果在 At() 中指定了已存在的数组的某个位置,那么那个位置上的值会被替换掉,请注意。
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() for i := 0; i < 10; i++ { v.SetInt(i).At("arr", i) } fmt.Println(v.MustMarshalString()) v.SetFloat64(123.12345).At("arr", 3) fmt.Println(v.MustMarshalString()) }
Output: {"arr":[0,1,2,3,4,5,6,7,8,9]} {"arr":[0,1,2,123.12345,4,5,6,7,8,9]}
type V ¶
type V struct {
// contains filtered or unexported fields
}
V is the main type of jsonvalue, representing a JSON value.
V 是 jsonvalue 的主类型,表示一个 JSON 值。
func Import ¶
Import convert json value from a marsalable parameter to *V.
Import 将符合 encoding/json 的 struct 转为 *jsonvalue.V 类型。该函数只是个便利的函数封装,途中需要一次序列化和反序列化, 性能不是最优。后续有计划改为无需序列化直接转换,并且支持浮点数的 Inf, -Inf, NaN 的特殊处理,敬请期待。
func MustUnmarshal ¶
MustUnmarshal just like Unmarshal(). If error occurres, a JSON value with "NotExist" type would be returned, which could do nothing and return nothing in later use. It is useful to shorten codes.
MustUnmarshal 的逻辑与 Unmarshal() 相同,不过如果错误的话,会返回一个类型未 "NotExist" 的 JSON 值,这个值在后续的操作中将无法返回 有效的数据,或者是执行任何有效的操作。但起码不会导致程序 panic,便于使用短代码实现一些默认逻辑。
func MustUnmarshalNoCopy ¶
MustUnmarshalNoCopy just like UnmarshalNoCopy(). If error occurres, a JSON value with "NotExist" type would be returned, which could do nothing and return nothing in later use. It is useful to shorten codes.
MustUnmarshalNoCopy 的逻辑与 UnmarshalNoCopy() 相同,不过如果错误的话,会返回一个类型未 "NotExist" 的 JSON 值,这个值在后续的操作中将无法返回 有效的数据,或者是执行任何有效的操作。但起码不会导致程序 panic,便于使用短代码实现一些默认逻辑。
func MustUnmarshalString ¶
MustUnmarshalString just like UnmarshalString(). If error occurres, a JSON value with "NotExist" type would be returned, which could do nothing and return nothing in later use. It is useful to shorten codes.
MustUnmarshalString 的逻辑与 UnmarshalString() 相同,不过如果错误的话,会返回一个类型未 "NotExist" 的 JSON 值,这个值在后续的操作中将无法返回 有效的数据,或者是执行任何有效的操作。但起码不会导致程序 panic,便于使用短代码实现一些默认逻辑。
func NewArray ¶
func NewArray() *V
NewArray returns an emty array-typed jsonvalue object
NewArray 返回一个初始化好的 array 类型的 jsonvalue 值。
func NewBool ¶
NewBool returns an initialied boolean jsonvalue object
NewBool 用给定的 bool 返回一个初始化好的布尔类型的 jsonvalue 值
func NewBytes ¶
NewBytes returns an initialized string with Base64 string by given bytes
NewBytes 用给定的字节串,返回一个初始化好的字符串类型的 jsonvalue 值,内容是字节串 Base64 之后的字符串。
func NewFloat32 ¶
NewFloat32 returns an initialied num jsonvalue value by float32 type. The format and precision control is the same with encoding/json: https://github.com/golang/go/blob/master/src/encoding/json/encode.go#L575
NewFloat32 根据指定的 float32 类型返回一个初始化好的数字类型的 jsonvalue 值。数字转出来的字符串格式参照 encoding/json 中的逻辑。
func NewFloat32f ¶
NewFloat32f returns an initialied num jsonvalue value by float64 type. The format and prec parameter are used in strconv.FormatFloat(). Only 'f', 'E', 'e', 'G', 'g' formats are supported, other formats will be mapped to 'g'.
NewFloat32f 根据指定的 float64 类型返回一个初始化好的数字类型的 jsonvalue 值。其中参数 format 和 prec 分别用于 strconv.FormatFloat() 函数. 只有 'f'、'E'、'e'、'G'、'g' 格式是支持的,其他配置均统一映射为 'g'。
func NewFloat64 ¶
NewFloat64 returns an initialied num jsonvalue value by float64 type. The format and precision control is the same with encoding/json: https://github.com/golang/go/blob/master/src/encoding/json/encode.go#L575
NewFloat64 根据指定的 flout64 类型返回一个初始化好的数字类型的 jsonvalue 值。数字转出来的字符串格式参照 encoding/json 中的逻辑。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { f := 123.123456789 var v *jsonvalue.V v = jsonvalue.NewFloat64(f) fmt.Println(v) v = jsonvalue.NewFloat64f(f, 'f', 6) fmt.Println(v) v = jsonvalue.NewFloat64f(f, 'e', 10) fmt.Println(v) }
Output: 123.123456789 123.123457 1.2312345679e+02
func NewFloat64f ¶
NewFloat64f returns an initialied num jsonvalue value by float64 type. The format and prec parameter are used in strconv.FormatFloat(). Only 'f', 'E', 'e', 'G', 'g' formats are supported, other formats will be mapped to 'g'.
NewFloat64f 根据指定的 float64 类型返回一个初始化好的数字类型的 jsonvalue 值。其中参数 format 和 prec 分别用于 strconv.FormatFloat() 函数. 只有 'f'、'E'、'e'、'G'、'g' 格式是支持的,其他配置均统一映射为 'g'。
func NewInt ¶
NewInt returns an initialied num jsonvalue object by int type
NewInt 用给定的 int 返回一个初始化好的数字类型的 jsonvalue 值
func NewInt32 ¶
NewInt32 returns an initialied num jsonvalue object by int32 type
NewInt32 用给定的 int32 返回一个初始化好的数字类型的 jsonvalue 值
func NewInt64 ¶
NewInt64 returns an initialied num jsonvalue object by int64 type
NewInt64 用给定的 int64 返回一个初始化好的数字类型的 jsonvalue 值
func NewNull ¶
func NewNull() *V
NewNull returns an initialied null jsonvalue object
NewNull 返回一个初始化好的 null 类型的 jsonvalue 值
func NewObject ¶
NewObject returns an object-typed jsonvalue object. If keyValues is specified, it will also create some key-values in the object. Now we supports basic types only. Such as int/uint, int/int8/int16/int32/int64, uint/uint8/uint16/uint32/uint64 series, string, bool, nil.
NewObject 返回一个初始化好的 object 类型的 jsonvalue 值。可以使用可选的 map[string]interface{} 类型参数初始化该 object 的下一级键值对, 不过目前只支持基础类型,也就是: int/uint, int/int8/int16/int32/int64, uint/uint8/uint16/uint32/uint64, string, bool, nil。
func NewString ¶
NewString returns an initialied string jsonvalue object
NewString 用给定的 string 返回一个初始化好的字符串类型的 jsonvalue 值
func NewUint ¶
NewUint returns an initialied num jsonvalue object by uint type
NewUint 用给定的 uint 返回一个初始化好的数字类型的 jsonvalue 值
func NewUint32 ¶
NewUint32 returns an initialied num jsonvalue object by uint32 type
NewUint32 用给定的 uint32 返回一个初始化好的数字类型的 jsonvalue 值
func NewUint64 ¶
NewUint64 returns an initialied num jsonvalue object by uint64 type
NewUint64 用给定的 uint64 返回一个初始化好的数字类型的 jsonvalue 值
func Unmarshal ¶
Unmarshal parse raw bytes(encoded in UTF-8 or pure AscII) and returns a *V instance.
Unmarshal 解析原始的字节类型数据(以 UTF-8 或纯 AscII 编码),并返回一个 *V 对象。
func UnmarshalNoCopy ¶
UnmarshalNoCopy is same as Unmarshal, but it does not copy another []byte instance for saving CPU time. But pay attention that the input []byte may be used as buffer by jsonvalue and mey be modified.
UnmarshalNoCopy 与 Unmarshal 相同,但是这个函数在解析过程中不会重新复制一个 []byte,对于大 json 的解析而言能够大大节省时间。 但请注意传入的 []byte 变量可能会被 jsonvalue 用作缓冲区,并进行修改
func UnmarshalString ¶
UnmarshalString is equavilent to Unmarshal([]byte(b)), but much more efficient.
UnmarshalString 等效于 Unmarshal([]byte(b)),但效率更高。
func (*V) Append ¶
Append starts appending a child JSON value to a JSON array.
Append 开始将一个 JSON 值添加到一个数组中。需结合 InTheEnd() 和 InTheBeginning() 函数使用。
func (*V) AppendArray ¶
AppendArray is equivalent to Append(jsonvalue.NewArray())
AppendArray 等价于 Append(jsonvalue.NewArray())
func (*V) AppendBool ¶
AppendBool is equivalent to Append(jsonvalue.NewBool(b))
AppendBool 等价于 Append(jsonvalue.NewBool(b))
func (*V) AppendBytes ¶
AppendBytes is equivalent to Append(jsonvalue.NewBytes(b))
AppendBytes 等价于 Append(jsonvalue.NewBytes(b))
func (*V) AppendFloat32 ¶
AppendFloat32 is equivalent to Append(jsonvalue.NewFloat32(b))
AppendFloat32 等价于 Append(jsonvalue.NewFloat32(b))
func (*V) AppendFloat64 ¶
AppendFloat64 is equivalent to Append(jsonvalue.NewFloat64(b))
AppendUint32 等价于 Append(jsonvalue.NewUint32(b))
func (*V) AppendInt ¶
AppendInt is equivalent to Append(jsonvalue.NewInt(b))
AppendInt 等价于 Append(jsonvalue.NewInt(b))
func (*V) AppendInt32 ¶
AppendInt32 is equivalent to Append(jsonvalue.NewInt32(b))
AppendInt32 等价于 Append(jsonvalue.NewInt32(b))
func (*V) AppendInt64 ¶
AppendInt64 is equivalent to Append(jsonvalue.NewInt64(b))
AppendInt64 等价于 Append(jsonvalue.NewInt64(b))
func (*V) AppendNull ¶
AppendNull is equivalent to Append(jsonvalue.NewNull())
AppendNull 等价于 Append(jsonvalue.NewNull())
func (*V) AppendObject ¶
AppendObject is equivalent to Append(jsonvalue.NewObject())
AppendObject 等价于 Append(jsonvalue.NewObject())
func (*V) AppendString ¶
AppendString is equivalent to Append(jsonvalue.NewString(s))
AppendString 等价于 Append(jsonvalue.NewString(s))
func (*V) AppendUint ¶
AppendUint is equivalent to Append(jsonvalue.NewUint(b))
AppendUint 等价于 Append(jsonvalue.NewUint(b))
func (*V) AppendUint32 ¶
AppendUint32 is equivalent to Append(jsonvalue.NewUint32(b))
AppendUint32 等价于 Append(jsonvalue.NewUint32(b))
func (*V) AppendUint64 ¶
AppendUint64 is equivalent to Append(jsonvalue.NewUint64(b))
AppendUint64 等价于 Append(jsonvalue.NewUint64(b))
func (*V) Bool ¶
Bool returns represented bool value. If value is not boolean, returns false.
Bool 返回布尔类型值。如果当前值不是布尔类型,则返回 false。
func (*V) Bytes ¶
Bytes returns represented binary data which is encoede as Base64 string. []byte{} would be returned if value is not a string type or base64 decode failed.
Bytes 返回以 Base64 编码在 string 类型中的二进制数据。如果当前值不是字符串类型,或者是 base64 编码失败,则返回 []byte{}。
func (*V) Caseless ¶
Caseless returns Caseless interface to support caseless getting.
IMPORTANT: This function is not gouroutine-safe. Write-mutex (instead of read-mutex) should be attached in cross-goroutine scenarios.
Caseless 返回 Caseless 接口,从而实现不区分大小写的 Get 操作。
注意: 该函数不是协程安全的,如果在多协程场景下,调用该函数,需要加上写锁,而不能用读锁。
func (*V) Delete ¶
Delete deletes specified JSON value. Forexample, parameters ("data", "list") identifies deleting value in data.list. While ("list", 1) means deleting 2nd (count from one) element from the "list" array.
Delete 从 JSON 中删除参数指定的对象。比如参数 ("data", "list") 表示删除 data.list 值;参数 ("list", 1) 则表示删除 list 数组的第2(从1算起)个值。
func (*V) Export ¶
Export convert jsonvalue to another type of parameter. The target parameter type should match the type of *V.
Export 将 *jsonvalue.V 转到符合原生 encoding/json 的一个 struct 中。该函数只是个便利的函数封装,途中需要一次序列化和反序列化, 性能不是最优。
func (*V) Float32 ¶
Float32 returns represented float32 value. If value is not a number, returns zero.
Float32 返回 float32 类型值。如果当前值不是数字类型,则返回 0.0。
func (*V) Float64 ¶
Float64 returns represented float64 value. If value is not a number, returns zero.
Float64 返回 float64 类型值。如果当前值不是数字类型,则返回 0.0。
func (*V) ForRangeArr ¶
ForRangeArr returns a slice which can be used in for - range block to iteration KVs in a JSON array value.
ForRangeObj 返回一个切片,用于使用 for - range 块迭代 JSON 数组类型的子成员。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `[1,2,3,4,5,6,7,8,9,10]` v, _ := jsonvalue.UnmarshalString(s) for i, v := range v.ForRangeArr() { fmt.Println(v) if i < 5 { // continue } else { break } } }
Output: 1 2 3 4 5 6
func (*V) ForRangeObj ¶
ForRangeObj returns a map which can be used in for - range block to iteration KVs in a JSON object value.
ForRangeObj 返回一个 map 类型,用于使用 for - range 块迭代 JSON 对象类型的子成员。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `{"message":"Hello, JSON!"}` v, _ := jsonvalue.UnmarshalString(s) for k, v := range v.ForRangeObj() { fmt.Println(k, "-", v) } }
Output: message - Hello, JSON!
func (*V) Get ¶
Get returns JSON value in specified position. Param formats are like At().
Get 返回按照参数指定的位置的 JSON 成员值。参数格式与 At() 函数相同
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `{"objA":{"objB":{"message":"Hello, world!"}}}` v, _ := jsonvalue.UnmarshalString(s) msg, _ := v.Get("objA", "objB", "message") fmt.Println(msg.String()) }
Output: Hello, world!
func (*V) GetArray ¶
GetArray is equalivent to v, err := Get(...); raise err if or v.IsArray() == false.
GetArray 等效于 v, err := Get(...);,如果发生错误或者 v.IsArray() == false 则返回错误。
func (*V) GetBool ¶
GetBool is equalivent to v, err := Get(...); v.Bool(). If error occurs, returns false.
GetBool 等效于 v, err := Get(...); v.Bool()。如果发生错误,则返回 false。
func (*V) GetBytes ¶
GetBytes is similar with v, err := Get(...); v.Bytes(). But if error occurs or Base64 decode error, returns error.
GetBytes 类似于 v, err := Get(...); v.Bytes(),但如果查询中发生错误,或者 base64 解码错误,则返回错误。
func (*V) GetFloat32 ¶
GetFloat32 is equalivent to v, err := Get(...); v.Float32(). If error occurs, returns 0.0.
GetFloat32 等效于 v, err := Get(...); v.Float32()。如果发生错误,则返回 0.0。
func (*V) GetFloat64 ¶
GetFloat64 is equalivent to v, err := Get(...); v.Float64(). If error occurs, returns 0.0.
GetFloat64 等效于 v, err := Get(...); v.Float64()。如果发生错误,则返回 0.0。
func (*V) GetInt ¶
GetInt is equalivent to v, err := Get(...); v.Int(). If error occurs, returns 0.
GetInt 等效于 v, err := Get(...); v.Int()。如果发生错误,则返回 0。
func (*V) GetInt32 ¶
GetInt32 is equalivent to v, err := Get(...); v.Int32(). If error occurs, returns 0.
GetInt32 等效于 v, err := Get(...); v.Int32()。如果发生错误,则返回 0。
func (*V) GetInt64 ¶
GetInt64 is equalivent to v, err := Get(...); v.Int64(). If error occurs, returns 0.
GetInt64 等效于 v, err := Get(...); v.Int64()。如果发生错误,则返回 0。
func (*V) GetNull ¶
GetNull is equalivent to v, err := Get(...); raise err if error occurs or v.IsNull() == false.
GetNull 等效于 v, err := Get(...);,如果发生错误或者 v.IsNull() == false 则返回错误。
func (*V) GetObject ¶
GetObject is equalivent to v, err := Get(...); raise err if error occurs or v.IsObject() == false.
GetObject 等效于 v, err := Get(...);,如果发生错误或者 v.IsObject() == false 则返回错误。
func (*V) GetString ¶
GetString is equalivent to v, err := Get(...); v.String(). If error occurs, returns "".
GetString 等效于 v, err := Get(...); v.String()。如果发生错误,则返回 ""。
func (*V) GetUint ¶
GetUint is equalivent to v, err := Get(...); v.Uint(). If error occurs, returns 0.
GetUint 等效于 v, err := Get(...); v.Uint()。如果发生错误,则返回 0。
func (*V) GetUint32 ¶
GetUint32 is equalivent to v, err := Get(...); v.Uint32(). If error occurs, returns 0.
GetUint32 等效于 v, err := Get(...); v.Uint32()。如果发生错误,则返回 0。
func (*V) GetUint64 ¶
GetUint64 is equalivent to v, err := Get(...); v.Unt64(). If error occurs, returns 0.
GetUint64 等效于 v, err := Get(...); v.Unt64()。如果发生错误,则返回 0。
func (*V) GreaterThanInt64Max ¶
GreaterThanInt64Max return true when ALL conditions below are met:
- It is a number value.
- It is a positive interger.
- Its value is greater than 0x7fffffffffffffff.
GreaterThanInt64Max 判断当前值是否超出 int64 可表示的范围。当以下条件均成立时,返回 true,否则返回 false:
- 是一个数字类型值.
- 是一个正整型数字.
- 该正整数的值大于 0x7fffffffffffffff.
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v1 := jsonvalue.NewUint64(uint64(9223372036854775808)) // 0x8000000000000000 v2 := jsonvalue.NewUint64(uint64(9223372036854775807)) // 0x7FFFFFFFFFFFFFFF v3 := jsonvalue.NewInt64(int64(-9223372036854775807)) fmt.Println(v1.GreaterThanInt64Max()) fmt.Println(v2.GreaterThanInt64Max()) fmt.Println(v3.GreaterThanInt64Max()) }
Output: true false false
func (*V) InsertArray ¶
InsertArray is equivalent to Insert(jsonvalue.NewArray())
InsertArray 等效于 Insert(jsonvalue.NewArray())
func (*V) InsertBool ¶
InsertBool is equivalent to Insert(jsonvalue.NewBool(b))
InsertBool 等效于 Insert(jsonvalue.NewBool(b))
func (*V) InsertFloat32 ¶
InsertFloat32 is equivalent to Insert(jsonvalue.NewFloat32(b))
InsertFloat32 等效于 Insert(jsonvalue.NewFloat32(b))
func (*V) InsertFloat64 ¶
InsertFloat64 is equivalent to Insert(jsonvalue.NewFloat64(b))
InsertFloat64 等效于 Insert(jsonvalue.NewFloat64(b))
func (*V) InsertInt ¶
InsertInt is equivalent to Insert(jsonvalue.NewInt(b))
InsertInt 等效于 Insert(jsonvalue.NewInt(b))
func (*V) InsertInt32 ¶
InsertInt32 is equivalent to Insert(jsonvalue.NewInt32(b))
InsertInt32 等效于 Insert(jsonvalue.NewInt32(b))
func (*V) InsertInt64 ¶
InsertInt64 is equivalent to Insert(jsonvalue.NewInt64(b))
InsertInt64 等效于 Insert(jsonvalue.NewInt64(b))
func (*V) InsertNull ¶
InsertNull is equivalent to Insert(jsonvalue.NewNull())
InsertNull 等效于 Insert(jsonvalue.NewNull())
func (*V) InsertObject ¶
InsertObject is equivalent to Insert(jsonvalue.NewObject())
InsertObject 等效于 Insert(jsonvalue.NewObject())
func (*V) InsertString ¶
InsertString is equivalent to Insert(jsonvalue.NewString(s))
InsertString 等效于 Insert(jsonvalue.NewString(s))
func (*V) InsertUint ¶
InsertUint is equivalent to Insert(jsonvalue.NewUint(b))
InsertUint 等效于 Insert(jsonvalue.NewUint(b))
func (*V) InsertUint32 ¶
InsertUint32 is equivalent to Insert(jsonvalue.NewUint32(b))
InsertUint32 等效于 Insert(jsonvalue.NewUint32(b))
func (*V) InsertUint64 ¶
InsertUint64 is equivalent to Insert(jsonvalue.NewUint64(b))
InsertUint64 等效于 Insert(jsonvalue.NewUint64(b))
func (*V) Int ¶
Int returns represented int value. If value is not a number, returns zero.
Int 返回 int 类型值。如果当前值不是数字类型,则返回 0。
func (*V) Int32 ¶
Int32 returns represented int32 value. If value is not a number, returns zero.
Int32 返回 int32 类型值。如果当前值不是数字类型,则返回 0。
func (*V) Int64 ¶
Int64 returns represented int64 value. If value is not a number, returns zero.
Int64 返回 int64 类型值。如果当前值不是数字类型,则返回 0。
func (*V) IsFloat ¶
IsFloat tells whether value is a float point number. If there is no decimal point in original text, it returns false while IsNumber returns true.
IsFloat 判断当前值是不是一个浮点数类型。如果给定的数不包含小数点,那么即便是数字类型,该函数也会返回 false.
func (*V) IsInteger ¶
IsInteger tells whether value is a fix point interger
IsNumber 判断当前值是不是一个定点数整型
func (*V) IterObjects
deprecated
func (v *V) IterObjects() <-chan *ObjectIter
Deprecated: IterObjects is deprecated, please Use ForRangeObj() instead.
func (*V) Len ¶
Len returns length of an object or array type JSON value.
Len 返回当前对象类型或数组类型的 JSON 的成员长度。如果不是这两种类型,那么会返回 0。
func (*V) MarshalString ¶
MarshalString is same with Marshal, but returns string. It is much more efficient than string(b).
MarshalString 与 Marshal 相同, 不同的是返回 string 类型。它比 string(b) 操作更高效。
func (*V) MustGet ¶
MustGet is same as Get(), but does not return error. If error occurs, a JSON value with NotExist type will be returned.
MustGet 与 Get() 函数相同,不过不返回错误。如果发生错误了,那么会返回一个 ValueType() 返回值为 NotExist 的 JSON 值对象。
func (*V) MustMarshal ¶
MustMarshal is the same as Marshal. If error pccurred, an empty byte slice will be returned.
MustMarshal 与 Marshal 相同,但是当错误发生时,什么都不做,直接返回空数据
func (*V) MustMarshalString ¶
MustMarshalString is the same as MarshalString, If error pccurred, an empty byte slice will be returned.
MustMarshalString 与 MarshalString 相同,但是当错误发生时,什么都不做,直接返回空数据
func (*V) RangeArray ¶
RangeArray goes through each children when this is an array value
Return true in callback to continue range iteration, while false to break.
若当前 JSON 值是一个 array 类型时,RangeArray 遍历所有的数组成员。
在回调函数中返回 true 表示继续迭代,返回 false 表示退出迭代
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `[1,2,3,4,5,6,7,8,9,10]` v, _ := jsonvalue.UnmarshalString(s) v.RangeArray(func(i int, v *jsonvalue.V) bool { fmt.Println(v) return i < 5 }) }
Output: 1 2 3 4 5 6
func (*V) RangeObjects ¶
RangeObjects goes through each children when this is an object value
Return true in callback to continue range iteration, while false to break.
若当前 JSON 值是一个 object 类型时,RangeObjects 遍历所有的键值对。
在回调函数中返回 true 表示继续迭代,返回 false 表示退出迭代
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { s := `{"message":"Hello, JSON!"}` v, _ := jsonvalue.UnmarshalString(s) v.RangeObjects(func(k string, v *jsonvalue.V) bool { fmt.Println(k, "-", v) return true }) }
Output: message - Hello, JSON!
func (*V) Set ¶
Set starts setting a child JSON value. Please refer to examples of "func (set *Set) At(...)"
https://godoc.org/github.com/Andrew-M-C/go.jsonvalue/#Set.At
Set 开始设置一个 JSON 子成员。请参见 "func (set *Set) At(...)" 例子.
https://godoc.org/github.com/Andrew-M-C/go.jsonvalue/#Set.At
func (*V) SetArray ¶
SetArray is equivalent to Set(jsonvalue.NewArray())
SetArray 等效于 Set(jsonvalue.NewArray())
func (*V) SetBool ¶
SetBool is equivalent to Set(jsonvalue.NewBool(b))
SetBool 等效于 Set(jsonvalue.NewBool(b))
func (*V) SetBytes ¶
SetBytes is equivalent to Set(NewString(base64.StdEncoding.EncodeToString(b)))
SetBytes 等效于 Set(NewString(base64.StdEncoding.EncodeToString(b)))
func (*V) SetFloat32 ¶
SetFloat32 is equivalent to Set(jsonvalue.NewFloat32(b))
SetFloat32 等效于 Set(jsonvalue.NewFloat32(b))
func (*V) SetFloat64 ¶
SetFloat64 is equivalent to Set(jsonvalue.NewFloat64(b))
SetFloat64 等效于 Set(jsonvalue.NewFloat64(b))
func (*V) SetInt ¶
SetInt is equivalent to Set(jsonvalue.NewInt(b))
SetInt 等效于 Set(jsonvalue.NewInt(b))
func (*V) SetInt32 ¶
SetInt32 is equivalent to Set(jsonvalue.NewInt32(b))
SetInt32 等效于 Set(jsonvalue.NewInt32(b))
func (*V) SetInt64 ¶
SetInt64 is equivalent to Set(jsonvalue.NewInt64(b))
SetInt64 等效于 Set(jsonvalue.NewInt64(b))
func (*V) SetNull ¶
SetNull is equivalent to Set(jsonvalue.NewNull())
SetNull 等效于 Set(jsonvalue.NewNull())
func (*V) SetObject ¶
SetObject is equivalent to Set(jsonvalue.NewObject())
SetObject 等效于 Set(jsonvalue.NewObject())
func (*V) SetString ¶
SetString is equivalent to Set(jsonvalue.NewString(s))
SetString 等效于 Set(jsonvalue.NewString(s))
func (*V) SetUint ¶
SetUint is equivalent to Set(jsonvalue.NewUint(b))
SetUint 等效于 Set(jsonvalue.NewUint(b))
func (*V) SetUint32 ¶
SetUint32 is equivalent to Set(jsonvalue.NewUint32(b))
SetUint32 等效于 Set(jsonvalue.NewUint32(b))
func (*V) SetUint64 ¶
SetUint64 is equivalent to Set(jsonvalue.NewUint64(b))
SetUint64 is equivalent to Set(jsonvalue.NewUint64(b))
func (*V) SortArray ¶
func (v *V) SortArray(lessFunc ArrayLessFunc)
SortArray is used to re-arrange sequence of the array. Invokers should pass less function for sorting. Nothing would happens either lessFunc is nil or v is not an array.
SortArray 用于对 array 类型的 JSON 的子成员进行重新排序。基本逻辑与 sort.Sort 函数相同。当 lessFunc 为 nil,或者当前 JSON 不是一个 array 类型时,什么变化都不会发生。
func (*V) String ¶
String returns represented string value or the description for the jsonvalue.V instance if it is not a string.
String 返回 string 类型值。如果当前值不是字符串类型,则返回当前 *V 类型的描述说明。
Example ¶
package main import ( "fmt" jsonvalue "gitee.com/Andrew-M-C/go.jsonvalue" ) func main() { v := jsonvalue.NewObject() v.SetString("Hello, string").At("object", "message") fmt.Println(v) child, _ := v.Get("object") fmt.Println(child) child, _ = v.Get("object", "message") fmt.Println(child) }
Output: {object: {message: Hello, string}} {message: Hello, string} Hello, string
func (*V) Uint ¶
Uint returns represented uint value. If value is not a number, returns zero.
Uint 返回 uint 类型值。如果当前值不是数字类型,则返回 0。
func (*V) Uint32 ¶
Uint32 returns represented uint32 value. If value is not a number, returns zero.
Uint32 返回 uint32 类型值。如果当前值不是数字类型,则返回 0。
type ValueType ¶
type ValueType int
ValueType identifying JSON value type
const ( // NotExist type tells that this JSON value is not exist or legal NotExist ValueType = iota // String JSON string type String // Number JSON number type Number // Object JSON object type Object // Array JSON array type Array // Boolean JSON boolean type Boolean // Null JSON null type Null // Unknown unknown JSON type Unknown )