jsonvalue

package module
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2024 License: MIT Imports: 15 Imported by: 14

README

Jsonvalue - A Fast and Convenient Alternation of Go map[string]interface{}

Workflow codecov Go report CodeBeat

GoDoc Latest License

Package jsonvalue is for handling unstructured JSON data or customizing JSON marshaling. It is far more faster and convenient than using interface{} with encoding/json.

Please refer to pkg site or wiki for detailed usage and examples.

Especially, please check for jsonvalue's programming scenarios.

Import

Use following statements to import jsonvalue:

import (
	jsonvalue "github.com/Andrew-M-C/go.jsonvalue"
)

Quick Start

Sometimes we want to create a complex JSON object like:

{
  "someObject": {
    "someObject": {
      "someObject": {
        "message": "Hello, JSON!"
      }
    }
  }
}

With jsonvalue, It is quite simple to implement this:

	v := jsonvalue.NewObject()
	v.MustSet("Hello, JSON").At("someObject", "someObject", "someObject", "message")
	fmt.Println(v.MustMarshalString())
	// Output:
	// {"someObject":{"someObject":{"someObject":{"message":"Hello, JSON!"}}}

Similarly, it is quite easy to create sub-arrays like:

[
  {
    "someArray": [
      "Hello, JSON!"
    ]
  }
]
	v := jsonvalue.NewArray()
	v.MustSet("Hello, JSON").At(0, "someObject", 0)
	fmt.Println(v.MustMarshalString())
	// Output:
	// [{"someObject":["Hello, JSON"]}]

In opposite, to parse and read the first JSON above, you can use jsonvalue like this:

	const raw = `{"someObject": {"someObject": {"someObject": {"message": "Hello, JSON!"}}}}`
	s := jsonvalue.MustUnmarshalString(s).GetString("someObject", "someObject", "someObject", "message")
	fmt.Println(s)
	// Output:
	// Hello, JSON!

However, it is quite complex and annoying in automatically creating array. I strongly suggest using SetArray() to create the array first, then use Append() or Insert() to set array elements. Please refer go godoc or Wiki.

Documentation

Overview

Package jsonvalue is for JSON parsing and setting. It is used in situations those Go structures cannot achieve, or "map[string]any" could not do properly.

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]any",但是后者也有很多不方便的地方。本包即是用于替代这些不方便的情况的。

快速上手:

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

Examples

Constants

View Source
const (
	// ErrNilParameter identifies input parameter 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")

	// ErrRawBytesUnrecognized identifies all unexpected raw bytes
	//
	// ErrRawBytesUnrecognized 表示无法识别的序列文本
	ErrRawBytesUnrecognized = 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")

	// ErrNotValidNullValue shows that a value starts with 'n' is not eventually a bool value
	//
	// ErrNotValidNullValue 表示当前不是一个 null 值类型的 JSON
	ErrNotValidNullValue = 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 valid 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")

	// ErrMultipleParamNotSupportedWithIfSliceOrArrayGiven indicates that if you
	// use a slice pr array as first param in Get(...), Set(...).At(...), etc, no
	// further params are allowed
	//
	// ErrMultipleParamNotSupportedWithIfSliceOrArrayGiven 表示如果你在使用 Get(...)、
	// Set(...).At(...) 等类似方法时, 首参数传入一个切片或数组, 那么不允许再传入更多的参数了
	ErrMultipleParamNotSupportedWithIfSliceOrArrayGiven = Error("if first param is a slice or array, no further param are allowed")

	// ErrParameterError indicates misc parameter error.
	//
	// ErrParameterError 表示各种参数错误
	ErrParameterError = Error("parameter error")
)

Variables

This section is empty.

Functions

func DefaultStringSequence added in v1.0.2

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 added in v1.2.1

func ResetDefaultMarshalOptions()

ResetDefaultMarshalOptions reset default marshaling options to system default.

ResetDefaultMarshalOptions 重设序列化时的默认选项为系统最原始的版本。

func SetDefaultMarshalOptions added in v1.2.1

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 Appender added in v1.3.4

type Appender interface {
	InTheBeginning(params ...any) (*V, error)
	InTheEnd(params ...any) (*V, error)
}

Appender type is for InTheEnd() or InTheBeginning() function.

Appender 类型是用于 InTheEnd() 和 InTheBeginning() 函数的。使用者可以不用关注这个类型。 并且这个类型只应当由 V.Append() 产生。

type ArrayIter deprecated added in v1.0.4

type ArrayIter struct {
	I int
	V *V
}

Deprecated: ArrayIter is a deprecated type.

type ArrayLessFunc added in v1.0.2

type ArrayLessFunc func(v1, v2 *V) bool

ArrayLessFunc is used in SortArray(), identifying which member is ahead.

ArrayLessFunc 用于 SortArray() 函数中,指定两个成员谁在前面。

type AtSetter added in v1.4.1

type AtSetter interface {
	Set(subValue any)
}

AtSetter works like v.MustSet(...).At(...), just with different sequence.

type Caseless added in v1.1.0

type Caseless interface {
	Get(firstParam any, otherParams ...any) (*V, error)
	MustGet(firstParam any, otherParams ...any) *V
	GetBytes(firstParam any, otherParams ...any) ([]byte, error)
	GetString(firstParam any, otherParams ...any) (string, error)
	GetInt(firstParam any, otherParams ...any) (int, error)
	GetUint(firstParam any, otherParams ...any) (uint, error)
	GetInt64(firstParam any, otherParams ...any) (int64, error)
	GetUint64(firstParam any, otherParams ...any) (uint64, error)
	GetInt32(firstParam any, otherParams ...any) (int32, error)
	GetUint32(firstParam any, otherParams ...any) (uint32, error)
	GetFloat64(firstParam any, otherParams ...any) (float64, error)
	GetFloat32(firstParam any, otherParams ...any) (float32, error)
	GetBool(firstParam any, otherParams ...any) (bool, error)
	GetNull(firstParam any, otherParams ...any) error
	GetObject(firstParam any, otherParams ...any) (*V, error)
	GetArray(firstParam any, otherParams ...any) (*V, error)

	Delete(firstParam any, otherParams ...any) error
	MustDelete(firstParam any, otherParams ...any)
}

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 equivalent 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

func (Error) Error

func (e Error) Error() string

type FloatInfHandleType added in v1.2.0

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 added in v1.2.0

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 Inserter added in v1.3.4

type Inserter interface {
	// After completes the following operation of Insert(). It inserts value AFTER
	//  specified position.
	//
	// The last parameter identifies the position where a new JSON is inserted after,
	//  it should ba an integer, no matter signed or unsigned. If the position is
	// zero or positive integer, 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 表示倒数第二个位置。
	After(firstParam any, otherParams ...any) (*V, error)

	// Before completes the following operation of Insert(). It inserts value BEFORE
	// specified position.
	//
	// The last parameter identifies the position where a new JSON is inserted after,
	// it should ba an integer, no matter signed or unsigned.
	// If the position is zero or positive integer, 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 表示倒数第二个位置。
	Before(firstParam any, otherParams ...any) (*V, error)
}

Inserter type is for After() and Before() methods.

Should be generated ONLY BY V.Insert() !

Insert 类型适用于 After() 和 Before() 方法。请注意:该类型仅应由 V.Insert 函数生成!

type Key added in v1.0.2

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

Key is the element of KeyPath

Key 是 KeyPath 类型的成员

func (*Key) Int added in v1.0.2

func (k *Key) Int() int

Int returns int value of a key.

Int 返回当前键值对的 int 值。

func (*Key) IsInt added in v1.0.2

func (k *Key) IsInt() bool

IsInt tells if current key is a integer, which indicates a child of an array

IsInt 判断当前的键是不是一个整型类型,如果是的话,那么它是一个 array JSON 的子成员。

func (*Key) IsString added in v1.0.2

func (k *Key) IsString() bool

IsString tells if current key is a string, which indicates a child of an object.

IsString 判断当前的键是不是一个 string 类型,如果是的话,那么它是一个 object JSON 的子成员。

func (*Key) String added in v1.0.2

func (k *Key) String() string

String returns string value of a key

String 返回当前键值对的键的描述

type KeyPath added in v1.0.2

type KeyPath []*Key

KeyPath identifies a full path of keys of object in jsonvalue.

KeyPath 表示一个对象在指定 jsonvalue 中的完整的键路径。

func (KeyPath) String added in v1.0.2

func (p KeyPath) String() (s string)

String returns last element of key path.

String 返回 KeyPath 的最后一个成员的描述。

type M added in v1.1.1

type M map[string]any

M is the alias of map[string]any

type MarshalLessFunc added in v1.0.2

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 MustAppender added in v1.3.4

type MustAppender interface {
	// InTheBeginning completes the following operation of Append().
	//
	// InTheBeginning 函数将 Append 函数指定的 JSON 值,添加到参数指定的数组的最前端
	InTheBeginning(params ...any)

	// InTheEnd completes the following operation of Append().
	//
	// InTheEnd 函数将 Append 函数指定的 JSON 值,添加到参数指定的数组的最后面
	InTheEnd(params ...any)
}

MustAppender is just like Appender, but not returning sub-value or error.

type MustInserter added in v1.3.4

type MustInserter interface {
	// After completes the following operation of Insert(). It inserts value AFTER
	// specified position.
	//
	// The last parameter identifies the position where a new JSON is inserted after,
	// it should ba an integer, no matter signed or unsigned. If the position is
	// zero or positive integer, 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 表示倒数第二个位置。
	After(firstParam any, otherParams ...any)

	// Before completes the following operation of Insert(). It inserts value BEFORE
	// specified position.
	//
	// The last parameter identifies the position where a new JSON is inserted after,
	// it should ba an integer, no matter signed or unsigned. If the position is
	// zero or positive integer, 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 表示倒数第二个位置。
	Before(firstParam any, otherParams ...any)
}

MustInserter is just like Inserter, but not returning sub-value or error.

type MustSetter added in v1.3.4

type MustSetter interface {
	// At completes the following operation of Set(). It defines position of value
	// in Set() and return the new value set.
	//
	// The usage of At() is perhaps the most important. This function will recursively
	// 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 值的子成员,并且设置到指定的位置上。设置的逻辑说明起来比较抽象,请打开以下的例子以了解,
	// 这非常重要。
	At(firstParam any, otherParams ...any)
}

MustSetter is just like Setter, but not returning sub-value or error.

type ObjectIter deprecated added in v1.0.4

type ObjectIter struct {
	K string
	V *V
}

Deprecated: ObjectIter is a deprecated type.

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 "github.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}
{}

type Option added in v1.2.0

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 added in v1.2.0

func OptDefaultStringSequence() Option

OptDefaultStringSequence configures MarshalLessFunc field in Opt{} as jsonvalue.DefaultStringSequence, which is dictionary sequence.

OptDefaultStringSequence 配置 Opt{} 中的 MarshalLessFunc 字段为 jsonvalue.DefaultStringSequence,也就是字典序。

func OptEscapeHTML added in v1.2.0

func OptEscapeHTML(on bool) Option

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 added in v1.2.1

func OptEscapeSlash(on bool) Option

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 "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()
	v.MustSetString("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 added in v1.2.0

func OptFloatInfToFloat(f float64) Option

OptFloatInfToFloat will replace a +Inf float value to specified f, while -f if the value is -Inf.

OptFloatInfToFloat 表示当遇到 +Inf 时,将其替换成另一个 float 值;如果是 -Inf,则会替换成其取负数。

func OptFloatInfToNull added in v1.2.0

func OptFloatInfToNull() Option

OptFloatInfToNull will replace a float value to null if it is +/-Inf.

OptFloatInfToNull 表示当遇到 +/-Inf 时,将值替换成 null

func OptFloatInfToString added in v1.2.0

func OptFloatInfToString(positiveInf, negativeInf string) Option

OptFloatInfToString tells what string to replace when marshaling +Inf and -Inf numbers.

OptFloatInfToString 表示遇到 +/-Inf 时,将其替换成什么字符串。

func OptFloatInfToStringInf added in v1.2.0

func OptFloatInfToStringInf() Option

OptFloatInfToStringInf will replace a +Inf value to string "+Inf", while -Inf to "-Inf"

OptFloatInfToStringInf 表示遇到 +/-Inf 时,相应地将其替换成字符串 "+Inf" 和 "-Inf"

func OptFloatNaNToFloat added in v1.2.0

func OptFloatNaNToFloat(f float64) Option

OptFloatNaNToFloat tells that when marshaling float NaN, replace it as another valid float number.

OptFloatNaNToFloat 指定当遇到 NaN 时,将值替换成一个有效的 float 值。

func OptFloatNaNToNull added in v1.2.0

func OptFloatNaNToNull() Option

OptFloatNaNToNull will replace a float value to null if it is NaN.

OptFloatNaNToNull 表示当遇到 NaN 时,将值替换成 null

func OptFloatNaNToString added in v1.2.0

func OptFloatNaNToString(s string) Option

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 added in v1.2.0

func OptFloatNaNToStringNaN() Option

OptFloatNaNToStringNaN will replace a float value to string "NaN" if it is NaN.

OptFloatNaNToStringNaN 表示遇到 NaN 时,将其替换成字符串 "NaN"

func OptIgnoreOmitempty added in v1.3.1

func OptIgnoreOmitempty() Option

OptIgnoreOmitempty is used in Import() and New() function. This option tells jsonvalue to ignore json tag "omitempty", which means that every field would be parsed into *jsonvalue.V.

OptIgnoreOmitempty 用在 Import 和 New() 函数中。这个选项将会忽略 json 标签中的 "omitempty" 参数。换句话说, 所有的字段都会被解析并包装到 *jsonvalue.V 值中。

func OptIndent added in v1.3.0

func OptIndent(prefix, indent string) Option

OptIndent appliesiIndent to format the output.

OptIndent 指定序列化时的缩进。

func OptKeySequence added in v1.2.0

func OptKeySequence(seq []string) Option

OptKeySequence configures MarshalKeySequence field in Opt{}.

OptKeySequence 配置 Opt{} 中的 MarshalKeySequence 字段。

func OptKeySequenceWithLessFunc added in v1.2.0

func OptKeySequenceWithLessFunc(f MarshalLessFunc) Option

OptKeySequenceWithLessFunc configures MarshalLessFunc field in Opt{}, which defines key sequence when marshaling.

OptKeySequenceWithLessFunc 配置 Opt{} 中的 MarshalLessFunc 字段,配置序列化时的键顺序。

func OptOmitNull added in v1.2.0

func OptOmitNull(b bool) Option

OptOmitNull configures OmitNull field in Opt{}, identifying whether null values should be omitted when marshaling.

OptOmitNull 配置 Opt{} 中的 OmitNull 字段,表示是否忽略 null 值。

func OptSetSequence added in v1.3.1

func OptSetSequence() Option

OptSetSequence tells that when marshaling an object, the key will be sorted by the time they are added into or refreshed in its parent object. The later a key

is set or updated, the later it and its value will be marshaled.

OptSetSequence 指定在序列化 object 时,按照一个 key 被设置时的顺序进行序列化。如果一个 key 越晚添加到 object 类型,则在序列化的时候越靠后。

func OptUTF8 added in v1.2.1

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 "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()
	v.MustSetString("🇺🇸🇨🇳🇷🇺🇬🇧🇫🇷").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 added in v1.0.2

type ParentInfo struct {
	Parent  *V
	KeyPath KeyPath
}

ParentInfo show information of parent of a JSON value.

ParentInfo 表示一个 JSON 值的父节点信息。

type Setter added in v1.3.4

type Setter interface {
	// At completes the following operation of Set(). It defines position of value
	// in Set() and return the new value set.
	//
	// The usage of At() is perhaps the most important. This function will recursively
	// 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 值的子成员,并且设置到指定的位置上。设置的逻辑说明起来比较抽象,请打开以下的例子以了解,
	// 这非常重要。
	At(firstParam any, otherParams ...any) (*V, error)
}

Setter type is for At() only.

Setter 类型仅用于 At() 函数。

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 added in v1.1.1

func Import(src any, opts ...Option) (*V, error)

Import convert json value from a marshal-able parameter to *V. This a experimental function.

Import 将符合 encoding/json 的 struct 转为 *V 类型。不经过 encoding/json,并且支持 Option.

func MustUnmarshal added in v1.1.1

func MustUnmarshal(b []byte) *V

MustUnmarshal just like Unmarshal(). If error occurs, 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 added in v1.1.1

func MustUnmarshalNoCopy(b []byte) *V

MustUnmarshalNoCopy just like UnmarshalNoCopy(). If error occurs, 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 added in v1.1.1

func MustUnmarshalString(s string) *V

MustUnmarshalString just like UnmarshalString(). If error occurs, 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 New added in v1.3.0

func New(value any) *V

New generate a new jsonvalue type via given type. If given type is not supported, the returned type would equal to NotExist. If you are not sure whether given value type is OK in runtime, use Import() instead.

New 函数按照给定参数类型创建一个 jsonvalue 类型。如果给定参数不是 JSON 支持的类型, 那么返回的 *V 对象的类型为 NotExist。如果在代码中无法确定入参是否是 JSON 支持的类型, 请改用函数 Import()。

func NewArray

func NewArray() *V

NewArray returns an empty array-typed jsonvalue object

NewArray 返回一个初始化好的 array 类型的 jsonvalue 值。

func NewBool

func NewBool(b bool) *V

NewBool returns an initialized boolean jsonvalue object

NewBool 用给定的 bool 返回一个初始化好的布尔类型的 jsonvalue 值

func NewBytes added in v1.2.0

func NewBytes(b []byte) *V

NewBytes returns an initialized string with Base64 string by given bytes

NewBytes 用给定的字节串,返回一个初始化好的字符串类型的 jsonvalue 值,内容是字节串 Base64 之后的字符串。

func NewFloat32

func NewFloat32(f float32) *V

NewFloat32 returns an initialized 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 added in v1.2.0

func NewFloat32f(f float32, format byte, prec int) *V

NewFloat32f returns an initialized 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

func NewFloat64(f float64) *V

NewFloat64 returns an initialized 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 "github.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 added in v1.2.0

func NewFloat64f(f float64, format byte, prec int) *V

NewFloat64f returns an initialized 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

func NewInt(i int) *V

NewInt returns an initialized num jsonvalue object by int type

NewInt 用给定的 int 返回一个初始化好的数字类型的 jsonvalue 值

func NewInt32

func NewInt32(i int32) *V

NewInt32 returns an initialized num jsonvalue object by int32 type

NewInt32 用给定的 int32 返回一个初始化好的数字类型的 jsonvalue 值

func NewInt64

func NewInt64(i int64) *V

NewInt64 returns an initialized num jsonvalue object by int64 type

NewInt64 用给定的 int64 返回一个初始化好的数字类型的 jsonvalue 值

func NewNull

func NewNull() *V

NewNull returns an initialized null jsonvalue object

NewNull 返回一个初始化好的 null 类型的 jsonvalue 值

func NewObject

func NewObject(keyValues ...M) *V

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]any 类型参数初始化该 object 的下一级键值对, 不过目前只支持基础类型,也就是: int/uint, int/int8/int16/int32/int64, uint/uint8/uint16/uint32/uint64, string, bool, nil。

func NewString

func NewString(s string) *V

NewString returns an initialized string jsonvalue object

NewString 用给定的 string 返回一个初始化好的字符串类型的 jsonvalue 值

func NewUint

func NewUint(u uint) *V

NewUint returns an initialized num jsonvalue object by uint type

NewUint 用给定的 uint 返回一个初始化好的数字类型的 jsonvalue 值

func NewUint32

func NewUint32(u uint32) *V

NewUint32 returns an initialized num jsonvalue object by uint32 type

NewUint32 用给定的 uint32 返回一个初始化好的数字类型的 jsonvalue 值

func NewUint64

func NewUint64(u uint64) *V

NewUint64 returns an initialized num jsonvalue object by uint64 type

NewUint64 用给定的 uint64 返回一个初始化好的数字类型的 jsonvalue 值

func Unmarshal

func Unmarshal(b []byte) (ret *V, err error)

Unmarshal parse raw bytes(encoded in UTF-8 or pure AscII) and returns a *V instance.

Unmarshal 解析原始的字节类型数据(以 UTF-8 或纯 AscII 编码),并返回一个 *V 对象。

func UnmarshalNoCopy added in v1.1.0

func UnmarshalNoCopy(b []byte) (ret *V, err error)

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

func UnmarshalString(s string) (*V, error)

UnmarshalString is equivalent to Unmarshal([]byte(b)), but more efficient.

UnmarshalString 等效于 Unmarshal([]byte(b)),但效率更高。

func (*V) Append

func (v *V) Append(child any) Appender

Append starts appending a child JSON value to a JSON array.

Append 开始将一个 JSON 值添加到一个数组中。需结合 InTheEnd() 和 InTheBeginning() 函数使用。

Example
package main

import (
	"fmt"

	jsonvalue "github.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 bebinning of v.obj.arr
	v.MustAppendInt(0).InTheBeginning("obj", "arr")
	fmt.Println(v.MustMarshalString())

	// append a zero in the end of v.obj.arr
	v.MustAppendInt(0).InTheEnd("obj", "arr")
	fmt.Println(v.MustMarshalString())

}
Output:

{"obj":{"arr":[0,1,2,3,4,5]}}
{"obj":{"arr":[0,1,2,3,4,5,0]}}

func (*V) AppendArray

func (v *V) AppendArray() Appender

AppendArray is equivalent to Append(jsonvalue.NewArray())

AppendArray 等价于 Append(jsonvalue.NewArray())

func (*V) AppendBool

func (v *V) AppendBool(b bool) Appender

AppendBool is equivalent to Append(jsonvalue.NewBool(b))

AppendBool 等价于 Append(jsonvalue.NewBool(b))

func (*V) AppendBytes added in v1.2.0

func (v *V) AppendBytes(b []byte) Appender

AppendBytes is equivalent to Append(jsonvalue.NewBytes(b))

AppendBytes 等价于 Append(jsonvalue.NewBytes(b))

func (*V) AppendFloat32

func (v *V) AppendFloat32(f float32) Appender

AppendFloat32 is equivalent to Append(jsonvalue.NewFloat32(b))

AppendFloat32 等价于 Append(jsonvalue.NewFloat32(b))

func (*V) AppendFloat64

func (v *V) AppendFloat64(f float64) Appender

AppendFloat64 is equivalent to Append(jsonvalue.NewFloat64(b))

AppendUint32 等价于 Append(jsonvalue.NewUint32(b))

func (*V) AppendInt

func (v *V) AppendInt(i int) Appender

AppendInt is equivalent to Append(jsonvalue.NewInt(b))

AppendInt 等价于 Append(jsonvalue.NewInt(b))

func (*V) AppendInt32

func (v *V) AppendInt32(i int32) Appender

AppendInt32 is equivalent to Append(jsonvalue.NewInt32(b))

AppendInt32 等价于 Append(jsonvalue.NewInt32(b))

func (*V) AppendInt64

func (v *V) AppendInt64(i int64) Appender

AppendInt64 is equivalent to Append(jsonvalue.NewInt64(b))

AppendInt64 等价于 Append(jsonvalue.NewInt64(b))

func (*V) AppendNull

func (v *V) AppendNull() Appender

AppendNull is equivalent to Append(jsonvalue.NewNull())

AppendNull 等价于 Append(jsonvalue.NewNull())

func (*V) AppendObject

func (v *V) AppendObject() Appender

AppendObject is equivalent to Append(jsonvalue.NewObject())

AppendObject 等价于 Append(jsonvalue.NewObject())

func (*V) AppendString

func (v *V) AppendString(s string) Appender

AppendString is equivalent to Append(jsonvalue.NewString(s))

AppendString 等价于 Append(jsonvalue.NewString(s))

func (*V) AppendUint

func (v *V) AppendUint(u uint) Appender

AppendUint is equivalent to Append(jsonvalue.NewUint(b))

AppendUint 等价于 Append(jsonvalue.NewUint(b))

func (*V) AppendUint32

func (v *V) AppendUint32(u uint32) Appender

AppendUint32 is equivalent to Append(jsonvalue.NewUint32(b))

AppendUint32 等价于 Append(jsonvalue.NewUint32(b))

func (*V) AppendUint64

func (v *V) AppendUint64(u uint64) Appender

AppendUint64 is equivalent to Append(jsonvalue.NewUint64(b))

AppendUint64 等价于 Append(jsonvalue.NewUint64(b))

func (*V) At added in v1.4.1

func (v *V) At(firstParam any, otherParams ...any) AtSetter

At works like v.MustSet(...).At(...), just with different sequence.

func (*V) Bool

func (v *V) Bool() bool

Bool returns represented bool value. If value is not boolean, returns false.

Bool 返回布尔类型值。如果当前值不是布尔类型,则判断是否为 string,不是 string 返回 false; 是 string 的话则返回字面值是否等于 true

func (*V) Bytes added in v1.1.0

func (v *V) Bytes() []byte

Bytes returns represented binary data which is encoded 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 added in v1.1.0

func (v *V) Caseless() 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

func (v *V) Delete(firstParam any, otherParams ...any) error

Delete deletes specified JSON value. For example, parameters ("data", "list") identifies deleting value in data.list. While ("list", 1) means deleting the second element from the "list" array.

Delete 从 JSON 中删除参数指定的对象。比如参数 ("data", "list") 表示删除 data.list 值;参数 ("list", 1) 则表示删除 list 数组的第2(从1算起)个值。

func (*V) Equal added in v1.3.0

func (v *V) Equal(another *V) bool

Equal shows whether the content of two JSON values equal to each other.

Equal 判断两个 JSON 的内容是否相等

func (*V) Export added in v1.1.1

func (v *V) Export(dst any) error

Export convert jsonvalue to another type of parameter. The target parameter type should match the type of *V.

Export 将 *V 转到符合原生 encoding/json 的一个 struct 中。

func (*V) Float32

func (v *V) Float32() float32

Float32 returns represented float32 value. If value is not a number, returns zero.

Float32 返回 float32 类型值。如果当前值不是数字类型,则返回 0.0。

func (*V) Float64

func (v *V) Float64() float64

Float64 returns represented float64 value. If value is not a number, returns zero.

Float64 返回 float64 类型值。如果当前值不是数字类型,则返回 0.0。

func (*V) ForRangeArr added in v1.2.0

func (v *V) ForRangeArr() []*V

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 "github.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 added in v1.2.0

func (v *V) ForRangeObj() map[string]*V

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 "github.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

func (v *V) Get(firstParam any, otherParams ...any) (*V, error)

Get returns JSON value in specified position. Param formats are like At().

Get 返回按照参数指定的位置的 JSON 成员值。参数格式与 At() 函数相同

Example
package main

import (
	"fmt"

	jsonvalue "github.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

func (v *V) GetArray(firstParam any, otherParams ...any) (*V, error)

GetArray is equivalent to v, err := Get(...); raise err if or v.IsArray() == false.

GetArray 等效于 v, err := Get(...);,如果发生错误或者 v.IsArray() == false 则返回错误。

func (*V) GetBool

func (v *V) GetBool(firstParam any, otherParams ...any) (bool, error)

GetBool is equivalent to v, err := Get(...); v.Bool(). If error occurs, returns false.

GetBool 等效于 v, err := Get(...); v.Bool()。如果发生错误,则返回 false。

func (*V) GetBytes added in v1.1.0

func (v *V) GetBytes(firstParam any, otherParams ...any) ([]byte, error)

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

func (v *V) GetFloat32(firstParam any, otherParams ...any) (float32, error)

GetFloat32 is equivalent to v, err := Get(...); v.Float32(). If error occurs, returns 0.0.

GetFloat32 等效于 v, err := Get(...); v.Float32()。如果发生错误,则返回 0.0。

func (*V) GetFloat64

func (v *V) GetFloat64(firstParam any, otherParams ...any) (float64, error)

GetFloat64 is equivalent to v, err := Get(...); v.Float64(). If error occurs, returns 0.0.

GetFloat64 等效于 v, err := Get(...); v.Float64()。如果发生错误,则返回 0.0。

func (*V) GetInt

func (v *V) GetInt(firstParam any, otherParams ...any) (int, error)

GetInt is equivalent to v, err := Get(...); v.Int(). If error occurs, returns 0.

GetInt 等效于 v, err := Get(...); v.Int()。如果发生错误,则返回 0。

func (*V) GetInt32

func (v *V) GetInt32(firstParam any, otherParams ...any) (int32, error)

GetInt32 is equivalent to v, err := Get(...); v.Int32(). If error occurs, returns 0.

GetInt32 等效于 v, err := Get(...); v.Int32()。如果发生错误,则返回 0。

func (*V) GetInt64

func (v *V) GetInt64(firstParam any, otherParams ...any) (int64, error)

GetInt64 is equivalent to v, err := Get(...); v.Int64(). If error occurs, returns 0.

GetInt64 等效于 v, err := Get(...); v.Int64()。如果发生错误,则返回 0。

func (*V) GetNull

func (v *V) GetNull(firstParam any, otherParams ...any) error

GetNull is equivalent to v, err := Get(...); raise err if error occurs or v.IsNull() == false.

GetNull 等效于 v, err := Get(...);,如果发生错误或者 v.IsNull() == false 则返回错误。

func (*V) GetObject

func (v *V) GetObject(firstParam any, otherParams ...any) (*V, error)

GetObject is equivalent to v, err := Get(...); raise err if error occurs or v.IsObject() == false.

GetObject 等效于 v, err := Get(...);,如果发生错误或者 v.IsObject() == false 则返回错误。

func (*V) GetString

func (v *V) GetString(firstParam any, otherParams ...any) (string, error)

GetString is equivalent to v, err := Get(...); v.String(). If error occurs, returns "".

GetString 等效于 v, err := Get(...); v.String()。如果发生错误,则返回 ""。

func (*V) GetUint

func (v *V) GetUint(firstParam any, otherParams ...any) (uint, error)

GetUint is equivalent to v, err := Get(...); v.Uint(). If error occurs, returns 0.

GetUint 等效于 v, err := Get(...); v.Uint()。如果发生错误,则返回 0。

func (*V) GetUint32

func (v *V) GetUint32(firstParam any, otherParams ...any) (uint32, error)

GetUint32 is equivalent to v, err := Get(...); v.Uint32(). If error occurs, returns 0.

GetUint32 等效于 v, err := Get(...); v.Uint32()。如果发生错误,则返回 0。

func (*V) GetUint64

func (v *V) GetUint64(firstParam any, otherParams ...any) (uint64, error)

GetUint64 is equivalent to v, err := Get(...); v.Unt64(). If error occurs, returns 0.

GetUint64 等效于 v, err := Get(...); v.Unt64()。如果发生错误,则返回 0。

func (*V) GreaterThan added in v1.4.0

func (v *V) GreaterThan(another *V) bool

GreaterThan returns whether v is greater than another value.

Both values should be number type, otherwise false will be returned.

func (*V) GreaterThanInt64Max

func (v *V) GreaterThanInt64Max() bool

GreaterThanInt64Max return true when ALL conditions below are met:

  1. It is a number value.
  2. It is a positive integer.
  3. Its value is greater than 0x7fffffffffffffff.

GreaterThanInt64Max 判断当前值是否超出 int64 可表示的范围。当以下条件均成立时,返回 true, 否则返回 false:

  1. 是一个数字类型值.
  2. 是一个正整型数字.
  3. 该正整数的值大于 0x7fffffffffffffff.
Example
package main

import (
	"fmt"

	jsonvalue "github.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) GreaterThanOrEqual added in v1.4.0

func (v *V) GreaterThanOrEqual(another *V) bool

GreaterThanOrEqual returns whether v is greater than or equal to another value.

Both values should be number type, otherwise false will be returned.

func (*V) Insert

func (v *V) Insert(child any) Inserter

Insert starts inserting a child JSON value

Insert 开启一个 JSON 数组成员的插入操作.

Example
package main

import (
	"fmt"

	jsonvalue "github.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.MustInsertString("my").After("obj", "arr", 0)
	fmt.Println(v.MustMarshalString())

	// insert a word in the middle, which is before the second word of the array
	v.MustInsertString("beautiful").Before("obj", "arr", 2)
	fmt.Println(v.MustMarshalString())

}
Output:

{"obj":{"arr":["hello","my","world"]}}
{"obj":{"arr":["hello","my","beautiful","world"]}}

func (*V) InsertArray

func (v *V) InsertArray() Inserter

InsertArray is equivalent to Insert(jsonvalue.NewArray())

InsertArray 等效于 Insert(jsonvalue.NewArray())

func (*V) InsertBool

func (v *V) InsertBool(b bool) Inserter

InsertBool is equivalent to Insert(jsonvalue.NewBool(b))

InsertBool 等效于 Insert(jsonvalue.NewBool(b))

func (*V) InsertFloat32

func (v *V) InsertFloat32(f float32) Inserter

InsertFloat32 is equivalent to Insert(jsonvalue.NewFloat32(b))

InsertFloat32 等效于 Insert(jsonvalue.NewFloat32(b))

func (*V) InsertFloat64

func (v *V) InsertFloat64(f float64) Inserter

InsertFloat64 is equivalent to Insert(jsonvalue.NewFloat64(b))

InsertFloat64 等效于 Insert(jsonvalue.NewFloat64(b))

func (*V) InsertInt

func (v *V) InsertInt(i int) Inserter

InsertInt is equivalent to Insert(jsonvalue.NewInt(b))

InsertInt 等效于 Insert(jsonvalue.NewInt(b))

func (*V) InsertInt32

func (v *V) InsertInt32(i int32) Inserter

InsertInt32 is equivalent to Insert(jsonvalue.NewInt32(b))

InsertInt32 等效于 Insert(jsonvalue.NewInt32(b))

func (*V) InsertInt64

func (v *V) InsertInt64(i int64) Inserter

InsertInt64 is equivalent to Insert(jsonvalue.NewInt64(b))

InsertInt64 等效于 Insert(jsonvalue.NewInt64(b))

func (*V) InsertNull

func (v *V) InsertNull() Inserter

InsertNull is equivalent to Insert(jsonvalue.NewNull())

InsertNull 等效于 Insert(jsonvalue.NewNull())

func (*V) InsertObject

func (v *V) InsertObject() Inserter

InsertObject is equivalent to Insert(jsonvalue.NewObject())

InsertObject 等效于 Insert(jsonvalue.NewObject())

func (*V) InsertString

func (v *V) InsertString(s string) Inserter

InsertString is equivalent to Insert(jsonvalue.NewString(s))

InsertString 等效于 Insert(jsonvalue.NewString(s))

func (*V) InsertUint

func (v *V) InsertUint(u uint) Inserter

InsertUint is equivalent to Insert(jsonvalue.NewUint(b))

InsertUint 等效于 Insert(jsonvalue.NewUint(b))

func (*V) InsertUint32

func (v *V) InsertUint32(u uint32) Inserter

InsertUint32 is equivalent to Insert(jsonvalue.NewUint32(b))

InsertUint32 等效于 Insert(jsonvalue.NewUint32(b))

func (*V) InsertUint64

func (v *V) InsertUint64(u uint64) Inserter

InsertUint64 is equivalent to Insert(jsonvalue.NewUint64(b))

InsertUint64 等效于 Insert(jsonvalue.NewUint64(b))

func (*V) Int

func (v *V) Int() int

Int returns represented int value. If value is not a number, returns zero.

Int 返回 int 类型值。如果当前值不是数字类型,则返回 0。

func (*V) Int32

func (v *V) Int32() int32

Int32 returns represented int32 value. If value is not a number, returns zero.

Int32 返回 int32 类型值。如果当前值不是数字类型,则返回 0。

func (*V) Int64

func (v *V) Int64() int64

Int64 returns represented int64 value. If value is not a number, returns zero.

Int64 返回 int64 类型值。如果当前值不是数字类型,则返回 0。

func (*V) IsArray

func (v *V) IsArray() bool

IsArray tells whether value is an array

IsArray 判断当前值是不是一个数组类型

func (*V) IsBoolean

func (v *V) IsBoolean() bool

IsBoolean tells whether value is a boolean

IsBoolean 判断当前值是不是一个布尔类型

func (*V) IsFloat

func (v *V) IsFloat() bool

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

func (v *V) IsInteger() bool

IsInteger tells whether value is a fix point integer

IsNumber 判断当前值是不是一个定点数整型

func (*V) IsNegative

func (v *V) IsNegative() bool

IsNegative tells whether value is a negative number

IsNegative 判断当前值是不是一个负数

func (*V) IsNull

func (v *V) IsNull() bool

IsNull tells whether value is a null

IsBoolean 判断当前值是不是一个空类型

func (*V) IsNumber

func (v *V) IsNumber() bool

IsNumber tells whether value is a number

IsNumber 判断当前值是不是一个数字类型

func (*V) IsObject

func (v *V) IsObject() bool

IsObject tells whether value is an object

IsObject 判断当前值是不是一个对象类型

func (*V) IsPositive

func (v *V) IsPositive() bool

IsPositive tells whether value is a positive number

IsPositive 判断当前值是不是一个正数

func (*V) IsString

func (v *V) IsString() bool

IsString tells whether value is a string

IsString 判断当前值是不是一个字符串类型

func (*V) IterArray deprecated added in v1.0.4

func (v *V) IterArray() <-chan *ArrayIter

Deprecated: IterArray is deprecated, please Use ForRangeArr() instead.

func (*V) IterObjects deprecated added in v1.0.4

func (v *V) IterObjects() <-chan *ObjectIter

Deprecated: IterObjects is deprecated, please Use ForRangeObj() instead.

func (*V) Len

func (v *V) Len() int

Len returns length of an object or array type JSON value.

Len 返回当前对象类型或数组类型的 JSON 的成员长度。如果不是这两种类型,那么会返回 0。

func (*V) LessThan added in v1.4.0

func (v *V) LessThan(another *V) bool

LessThan returns whether v is less than another value.

Both values should be number type, otherwise false will be returned.

func (*V) LessThanOrEqual added in v1.4.0

func (v *V) LessThanOrEqual(another *V) bool

LessThanOrEqual returns whether v is less than or equal to another value.

Both values should be number type, otherwise false will be returned.

func (*V) Marshal

func (v *V) Marshal(opts ...Option) (b []byte, err error)

Marshal returns marshaled bytes.

Marshal 返回序列化后的 JSON 字节序列。

func (*V) MarshalBinary added in v1.3.4

func (v *V) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler

func (*V) MarshalJSON added in v1.3.4

func (v *V) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (*V) MarshalString

func (v *V) MarshalString(opts ...Option) (s string, err error)

MarshalString is same with Marshal, but returns string. It is much more efficient than string(b).

MarshalString 与 Marshal 相同, 不同的是返回 string 类型。它比 string(b) 操作更高效。

func (*V) MustAppend added in v1.3.4

func (v *V) MustAppend(child any) MustAppender

Append starts appending a child JSON value to a JSON array.

Append 开始将一个 JSON 值添加到一个数组中。需结合 InTheEnd() 和 InTheBeginning() 函数使用。

func (*V) MustAppendArray added in v1.3.4

func (v *V) MustAppendArray() MustAppender

MustAppendArray is just like AppendArray, but not returning sub-value or error.

func (*V) MustAppendBool added in v1.3.4

func (v *V) MustAppendBool(b bool) MustAppender

MustAppendBool is just like AppendBool, but not returning sub-value or error.

func (*V) MustAppendBytes added in v1.3.4

func (v *V) MustAppendBytes(b []byte) MustAppender

MustAppendBytes is just like AppendBytes, but not returning sub-value or error.

func (*V) MustAppendFloat32 added in v1.3.4

func (v *V) MustAppendFloat32(f float32) MustAppender

MustAppendFloat32 is just like AppendFloat32, but not returning sub-value or error.

func (*V) MustAppendFloat64 added in v1.3.4

func (v *V) MustAppendFloat64(f float64) MustAppender

MustAppendFloat64 is just like AppendFloat64, but not returning sub-value or error.

func (*V) MustAppendInt added in v1.3.4

func (v *V) MustAppendInt(i int) MustAppender

MustAppendInt is just like AppendInt, but not returning sub-value or error.

func (*V) MustAppendInt32 added in v1.3.4

func (v *V) MustAppendInt32(i int32) MustAppender

MustAppendInt32 is just like AppendInt32, but not returning sub-value or error.

func (*V) MustAppendInt64 added in v1.3.4

func (v *V) MustAppendInt64(i int64) MustAppender

MustAppendInt64 is just like AppendInt64, but not returning sub-value or error.

func (*V) MustAppendNull added in v1.3.4

func (v *V) MustAppendNull() MustAppender

MustAppendNull is just like AppendNull, but not returning sub-value or error.

func (*V) MustAppendObject added in v1.3.4

func (v *V) MustAppendObject() MustAppender

MustAppendObject is just like AppendObject, but not returning sub-value or error.

func (*V) MustAppendString added in v1.3.4

func (v *V) MustAppendString(s string) MustAppender

MustAppendString is just like AppendString, but not returning sub-value or error.

func (*V) MustAppendUint added in v1.3.4

func (v *V) MustAppendUint(u uint) MustAppender

MustAppendUint is just like AppendUint, but not returning sub-value or error.

func (*V) MustAppendUint32 added in v1.3.4

func (v *V) MustAppendUint32(u uint32) MustAppender

MustAppendUint32 is just like AppendUint32, but not returning sub-value or error.

func (*V) MustAppendUint64 added in v1.3.4

func (v *V) MustAppendUint64(u uint64) MustAppender

MustAppendUint64 is just like AppendUint64, but not returning sub-value or error.

func (*V) MustDelete added in v1.3.4

func (v *V) MustDelete(firstParam any, otherParams ...any)

MustDelete is just like Delete, but not returning error.

func (*V) MustGet added in v1.1.1

func (v *V) MustGet(firstParam any, otherParams ...any) *V

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) MustInsert added in v1.3.4

func (v *V) MustInsert(child any) MustInserter

MustInsert is just like Insert, but not returning sub-value or error.

func (*V) MustInsertArray added in v1.3.4

func (v *V) MustInsertArray() MustInserter

MustInsertArray is just like InsertArray, but not returning sub-value or error.

func (*V) MustInsertBool added in v1.3.4

func (v *V) MustInsertBool(b bool) MustInserter

MustInsertBool is just like InsertBool, but not returning sub-value or error.

func (*V) MustInsertFloat32 added in v1.3.4

func (v *V) MustInsertFloat32(f float32) MustInserter

MustInsertFloat32 is just like InsertFloat32, but not returning sub-value or error.

func (*V) MustInsertFloat64 added in v1.3.4

func (v *V) MustInsertFloat64(f float64) MustInserter

MustInsertFloat64 is just like InsertFloat64, but not returning sub-value or error.

func (*V) MustInsertInt added in v1.3.4

func (v *V) MustInsertInt(i int) MustInserter

MustInsertInt is just like InsertInt, but not returning sub-value or error.

func (*V) MustInsertInt32 added in v1.3.4

func (v *V) MustInsertInt32(i int32) MustInserter

MustInsertInt32 is just like InsertInt32, but not returning sub-value or error.

func (*V) MustInsertInt64 added in v1.3.4

func (v *V) MustInsertInt64(i int64) MustInserter

MustInsertInt64 is just like InsertInt64, but not returning sub-value or error.

func (*V) MustInsertNull added in v1.3.4

func (v *V) MustInsertNull() MustInserter

MustInsertNull is just like InsertNull, but not returning sub-value or error.

func (*V) MustInsertObject added in v1.3.4

func (v *V) MustInsertObject() MustInserter

MustInsertObject is just like InsertObject, but not returning sub-value or error.

func (*V) MustInsertString added in v1.3.4

func (v *V) MustInsertString(s string) MustInserter

MustInsertString is just like InsertString, but not returning sub-value or error.

func (*V) MustInsertUint added in v1.3.4

func (v *V) MustInsertUint(u uint) MustInserter

MustInsertUint is just like InsertUint, but not returning sub-value or error.

func (*V) MustInsertUint32 added in v1.3.4

func (v *V) MustInsertUint32(u uint32) MustInserter

MustInsertUint32 is just like InsertUint32, but not returning sub-value or error.

func (*V) MustInsertUint64 added in v1.3.4

func (v *V) MustInsertUint64(u uint64) MustInserter

MustInsertUint64 is just like InsertUint64, but not returning sub-value or error.

func (*V) MustMarshal

func (v *V) MustMarshal(opts ...Option) []byte

MustMarshal is the same as Marshal. If error occurs, an empty byte slice will be returned.

MustMarshal 与 Marshal 相同,但是当错误发生时,什么都不做,直接返回空数据

func (*V) MustMarshalString

func (v *V) MustMarshalString(opt ...Option) string

MustMarshalString is the same as MarshalString, If error occurs, an empty byte slice will be returned.

MustMarshalString 与 MarshalString 相同,但是当错误发生时,什么都不做,直接返回空数据

func (*V) MustSet added in v1.3.4

func (v *V) MustSet(child any) MustSetter

MustSet is just like Set, but not returning sub-value or error.

func (*V) MustSetArray added in v1.3.4

func (v *V) MustSetArray() MustSetter

MustSetArray is equivalent to Set(jsonvalue.NewArray())

MustSetArray 等效于 Set(jsonvalue.NewArray())

func (*V) MustSetBool added in v1.3.4

func (v *V) MustSetBool(b bool) MustSetter

MustSetBool is equivalent to Set(jsonvalue.NewBool(b))

MustSetBool 等效于 Set(jsonvalue.NewBool(b))

func (*V) MustSetBytes added in v1.3.4

func (v *V) MustSetBytes(b []byte) MustSetter

MustSetBytes is equivalent to Set(NewString(base64.StdEncoding.EncodeToString(b)))

MustSetBytes 等效于 Set(NewString(base64.StdEncoding.EncodeToString(b)))

func (*V) MustSetFloat32 added in v1.3.4

func (v *V) MustSetFloat32(f float32) MustSetter

MustSetFloat32 is equivalent to Set(jsonvalue.NewFloat32(b))

MustSetFloat32 等效于 Set(jsonvalue.NewFloat32(b))

func (*V) MustSetFloat64 added in v1.3.4

func (v *V) MustSetFloat64(f float64) MustSetter

MustSetFloat64 is equivalent to Set(jsonvalue.NewFloat64(b))

MustSetFloat64 等效于 Set(jsonvalue.NewFloat64(b))

func (*V) MustSetInt added in v1.3.4

func (v *V) MustSetInt(i int) MustSetter

MustSetInt is equivalent to Set(jsonvalue.NewInt(b))

MustSetInt 等效于 Set(jsonvalue.NewInt(b))

func (*V) MustSetInt32 added in v1.3.4

func (v *V) MustSetInt32(i int32) MustSetter

MustSetInt32 is equivalent to Set(jsonvalue.NewInt32(b))

MustSetInt32 等效于 Set(jsonvalue.NewInt32(b))

func (*V) MustSetInt64 added in v1.3.4

func (v *V) MustSetInt64(i int64) MustSetter

MustSetInt64 is equivalent to Set(jsonvalue.NewInt64(b))

MustSetInt64 等效于 Set(jsonvalue.NewInt64(b))

func (*V) MustSetNull added in v1.3.4

func (v *V) MustSetNull() MustSetter

MustSetNull is equivalent to Set(jsonvalue.NewNull())

MustSetNull 等效于 Set(jsonvalue.NewNull())

func (*V) MustSetObject added in v1.3.4

func (v *V) MustSetObject() MustSetter

MustSetObject is equivalent to Set(jsonvalue.NewObject())

MustSetObject 等效于 Set(jsonvalue.NewObject())

func (*V) MustSetString added in v1.3.4

func (v *V) MustSetString(s string) MustSetter

MustSetString is equivalent to Set(jsonvalue.NewString(s))

MustSetString 等效于 Set(jsonvalue.NewString(s))

func (*V) MustSetUint added in v1.3.4

func (v *V) MustSetUint(u uint) MustSetter

MustSetUint is equivalent to Set(jsonvalue.NewUint(b))

MustSetUint 等效于 Set(jsonvalue.NewUint(b))

func (*V) MustSetUint32 added in v1.3.4

func (v *V) MustSetUint32(u uint32) MustSetter

MustSetUint32 is equivalent to Set(jsonvalue.NewUint32(b))

MustSetUint32 等效于 Set(jsonvalue.NewUint32(b))

func (*V) MustSetUint64 added in v1.3.4

func (v *V) MustSetUint64(u uint64) MustSetter

MustSetUint64 is equivalent to Set(jsonvalue.NewUint64(b))

MustSetUint64 is equivalent to Set(jsonvalue.NewUint64(b))

func (*V) RangeArray

func (v *V) RangeArray(callback func(i int, v *V) bool)

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 "github.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

func (v *V) RangeObjects(callback func(k string, v *V) bool)

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 "github.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) RangeObjectsBySetSequence added in v1.3.1

func (v *V) RangeObjectsBySetSequence(callback func(k string, v *V) bool)

RangeObjectsBySetSequence acts just like RangeObjects, but the key sequence is arranged by when a key is set to the given object.

RangeObjectsBySetSequence 类似于 RangeObjects 函数, 但是 key 的顺序会依照其被 set 进这个 object 的顺序传递。

func (*V) Set

func (v *V) Set(child any) Setter

Set starts setting a child JSON value. Any legal JSON value typped parameter is accepted, such as string, int, float, bool, nil, *jsonvalue.V, or even a struct or map or slice.

Please refer to examples of "func (set Setter) At(...)"

https://godoc.org/github.com/Andrew-M-C/go.jsonvalue/#Set.At

Set 开始设置一个 JSON 子成员。任何合法的 JSON 类型都可以作为参数, 比如 string, int, float, bool, nil, *jsonvalue.V 等类型, 甚至也支持结构体、map、切片、数组。

请参见 "func (set Setter) At(...)" 例子.

https://godoc.org/github.com/Andrew-M-C/go.jsonvalue/#Set.At

Example

For a simplest example:

这是最简单的例子:

package main

import (
	"fmt"

	jsonvalue "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()                      // {}
	v.MustSetObject().At("obj")                     // {"obj":{}}
	v.MustSet("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 "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()                      // {}
	v.MustSet("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 "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()              // {}
	v.MustSet("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 "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()                   // {}
	_, err := v.Set("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.MustSet(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 "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()
	for i := 0; i < 10; i++ {
		v.MustSetInt(i).At("arr", i)
	}

	fmt.Println(v.MustMarshalString())

	v.MustSet(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]}
Example (Another5)

In addition, any legal json type parameters are supported in Set(...).At(...). For example, we can set a struct as following:

此外,Set(...).At(...) 支持任意合法的 json 类型变量参数。比如我可以传入一个结构体:

package main

import (
	"fmt"

	jsonvalue "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	type st struct {
		Text string `json:"text"`
	}
	child := st{
		Text: "Hello, jsonvalue!",
	}
	v := jsonvalue.NewObject()
	v.MustSet(child).At("child")
	fmt.Println(v.MustMarshalString())
}
Output:

{"child":{"text":"Hello, jsonvalue!"}}

func (*V) SetArray

func (v *V) SetArray() Setter

SetArray is equivalent to Set(jsonvalue.NewArray())

SetArray 等效于 Set(jsonvalue.NewArray())

func (*V) SetBool

func (v *V) SetBool(b bool) Setter

SetBool is equivalent to Set(jsonvalue.NewBool(b))

SetBool 等效于 Set(jsonvalue.NewBool(b))

func (*V) SetBytes added in v1.1.0

func (v *V) SetBytes(b []byte) Setter

SetBytes is equivalent to Set(NewString(base64.StdEncoding.EncodeToString(b)))

SetBytes 等效于 Set(NewString(base64.StdEncoding.EncodeToString(b)))

func (*V) SetFloat32

func (v *V) SetFloat32(f float32) Setter

SetFloat32 is equivalent to Set(jsonvalue.NewFloat32(b))

SetFloat32 等效于 Set(jsonvalue.NewFloat32(b))

func (*V) SetFloat64

func (v *V) SetFloat64(f float64) Setter

SetFloat64 is equivalent to Set(jsonvalue.NewFloat64(b))

SetFloat64 等效于 Set(jsonvalue.NewFloat64(b))

func (*V) SetInt

func (v *V) SetInt(i int) Setter

SetInt is equivalent to Set(jsonvalue.NewInt(b))

SetInt 等效于 Set(jsonvalue.NewInt(b))

func (*V) SetInt32

func (v *V) SetInt32(i int32) Setter

SetInt32 is equivalent to Set(jsonvalue.NewInt32(b))

SetInt32 等效于 Set(jsonvalue.NewInt32(b))

func (*V) SetInt64

func (v *V) SetInt64(i int64) Setter

SetInt64 is equivalent to Set(jsonvalue.NewInt64(b))

SetInt64 等效于 Set(jsonvalue.NewInt64(b))

func (*V) SetNull

func (v *V) SetNull() Setter

SetNull is equivalent to Set(jsonvalue.NewNull())

SetNull 等效于 Set(jsonvalue.NewNull())

func (*V) SetObject

func (v *V) SetObject() Setter

SetObject is equivalent to Set(jsonvalue.NewObject())

SetObject 等效于 Set(jsonvalue.NewObject())

func (*V) SetString

func (v *V) SetString(s string) Setter

SetString is equivalent to Set(jsonvalue.NewString(s))

SetString 等效于 Set(jsonvalue.NewString(s))

func (*V) SetUint

func (v *V) SetUint(u uint) Setter

SetUint is equivalent to Set(jsonvalue.NewUint(b))

SetUint 等效于 Set(jsonvalue.NewUint(b))

func (*V) SetUint32

func (v *V) SetUint32(u uint32) Setter

SetUint32 is equivalent to Set(jsonvalue.NewUint32(b))

SetUint32 等效于 Set(jsonvalue.NewUint32(b))

func (*V) SetUint64

func (v *V) SetUint64(u uint64) Setter

SetUint64 is equivalent to Set(jsonvalue.NewUint64(b))

SetUint64 is equivalent to Set(jsonvalue.NewUint64(b))

func (*V) SortArray added in v1.0.2

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

func (v *V) String() 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 "github.com/Andrew-M-C/go.jsonvalue"
)

func main() {
	v := jsonvalue.NewObject()
	v.MustSetString("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

func (v *V) Uint() uint

Uint returns represented uint value. If value is not a number, returns zero.

Uint 返回 uint 类型值。如果当前值不是数字类型,则返回 0。

func (*V) Uint32

func (v *V) Uint32() uint32

Uint32 returns represented uint32 value. If value is not a number, returns zero.

Uint32 返回 uint32 类型值。如果当前值不是数字类型,则返回 0。

func (*V) Uint64

func (v *V) Uint64() uint64

Uint64 returns represented uint64 value. If value is not a number, returns zero.

Uint64 返回 uint64 类型值。如果当前值不是数字类型,则返回 0。

func (*V) UnmarshalBinary added in v1.3.4

func (v *V) UnmarshalBinary(b []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler

func (*V) UnmarshalJSON added in v1.3.4

func (v *V) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler

func (*V) ValueType added in v1.1.0

func (v *V) ValueType() ValueType

ValueType returns the type of this JSON value.

type ValueType added in v1.1.0

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
)

func (ValueType) String added in v1.1.1

func (t ValueType) String() string

String show the type name of JSON

Directories

Path Synopsis
Package beta contains some beta features of jsonvalue.
Package beta contains some beta features of jsonvalue.
internal
buffer
Package buffer implements a marshaling buffer for jsonvalue
Package buffer implements a marshaling buffer for jsonvalue

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL