Documentation
¶
Overview ¶
Package gjson provides searching for json strings.
Index ¶
- func AddModifier(name string, fn func(json, arg string) string)
- func AppendJSONString(dst []byte, s string) []byte
- func Escape(comp string) string
- func ForEachLine(json string, iterator func(line Result) bool)
- func ModifierExists(name string, fn func(json, arg string) string) bool
- func SetEscapeHTML(escapeHTML bool)
- func Valid(json string) bool
- func ValidBytes(json []byte) bool
- type Result
- func Get(json, path string) Result
- func GetBytes(json []byte, path string) Result
- func GetMany(json string, path ...string) []Result
- func GetManyBytes(json []byte, path ...string) []Result
- func GetManyKeys(json string, keys []string, dst []Result) []Result
- func Parse(json string) Result
- func ParseBytes(json []byte) Result
- func (t Result) All() iter.Seq2[Result, Result]
- func (t Result) Array() []Result
- func (t Result) Bool() bool
- func (t Result) Exists() bool
- func (t Result) Float() float64
- func (t Result) ForEach(iterator func(key, value Result) bool)
- func (t Result) Get(path string) Result
- func (t Result) Int() int64
- func (t Result) IsArray() bool
- func (t Result) IsBool() bool
- func (t Result) IsObject() bool
- func (t Result) Keys() iter.Seq[Result]
- func (t Result) Less(token Result, caseSensitive bool) bool
- func (t Result) Map() map[string]Result
- func (t Result) Path(json string) string
- func (t Result) Paths(json string) []string
- func (t Result) String() string
- func (t Result) Time() time.Time
- func (t Result) Uint() uint64
- func (t Result) Value() any
- func (t Result) Values() iter.Seq[Result]
- type Type
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddModifier ¶
AddModifier binds a custom modifier command to the GJSON syntax. Provide the name of the modifier without the '@' prefix. 内置修饰符 (如 pretty/this/valid) 不可覆盖, 同名注册会被忽略. 可与查询并发调用; 同名自定义修饰符以最后一次注册为准. 每次注册都复制整张自定义表 (写时复制), 适合启动期或低频注册, 不宜在热路径反复调用.
func AppendJSONString ¶
AppendJSONString is a convenience function that converts the provided string to a valid JSON string and appends it to dst.
func Escape ¶
Escape returns an escaped path component.
json := `{
"user":{
"first.name": "Janet",
"last.name": "Prichard"
}
}`
user := gjson.Get(json, "user")
println(user.Get(gjson.Escape("first.name")).String())
println(user.Get(gjson.Escape("last.name")).String())
// Output:
// Janet
// Prichard
func ForEachLine ¶
ForEachLine iterates through lines of JSON as specified by the JSON Lines format (http://jsonlines.org/). Each line is returned as a GJSON Result.
func ModifierExists ¶
ModifierExists returns true when the specified modifier exists.
func SetEscapeHTML ¶ added in v1.4.3
func SetEscapeHTML(escapeHTML bool)
SetEscapeHTML 设置编码 JSON 字符串时是否转义 HTML 敏感字符, 运行期可并发调用. 默认转义, 将 '>', '<' 和 '&' 分别写为 \u003e, \u003c 和 \u0026.
func Valid ¶
Valid returns true if the input is valid json.
if !gjson.Valid(json) {
return errors.New("invalid json")
}
value := gjson.Get(json, "name.last")
func ValidBytes ¶
ValidBytes returns true if the input is valid json.
if !gjson.Valid(json) {
return errors.New("invalid json")
}
value := gjson.Get(json, "name.last")
If working with bytes, this method preferred over ValidBytes(string(data))
Types ¶
type Result ¶
type Result struct {
// Type is the json type
Type Type
// Raw is the raw json
Raw string
// Str is the json string
Str string
// Num is the json number
Num float64
// Index of raw value in original json, zero means index unknown
Index int
// Indexes of all the elements that match on a path containing the '#'
// query character.
Indexes []int
}
Result represents a json value that is returned from Get().
func Get ¶
Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". When the value is found it's returned immediately.
A path is a series of keys separated by a dot. A key may contain special wildcard characters '*' and '?'. To access an array value use the index as the key. To get the number of elements in an array or to access a child path, use the '#' character. The dot and wildcard character can be escaped with '\'.
{
"name": {"first": "Tom", "last": "Anderson"},
"age":37,
"children": ["Sara","Alex","Jack"],
"friends": [
{"first": "James", "last": "Murphy"},
{"first": "Roger", "last": "Craig"}
]
}
"name.last" >> "Anderson"
"age" >> 37
"children" >> ["Sara","Alex","Jack"]
"children.#" >> 3
"children.1" >> "Alex"
"child*.2" >> "Jack"
"c?ildren.0" >> "Sara"
"friends.#.first" >> ["James","Roger"]
This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first.
func GetBytes ¶
GetBytes searches json for the specified path. If working with bytes, this method preferred over Get(string(data), path)
func GetMany ¶
GetMany searches json for the multiple paths. The return value is a Result array where the number of items will be equal to the number of input paths.
func GetManyBytes ¶
GetManyBytes searches json for the multiple paths. The return value is a Result array where the number of items will be equal to the number of input paths.
func GetManyKeys ¶ added in v1.4.3
GetManyKeys 一次扫描顶层 JSON 对象, 取出多个顶层字面量键的值. 本函数是本地扩展, 上游没有对应 API.
keys 中的每个键按字面量匹配, 不解析路径语法: 键 "a.b" 只匹配名为 "a.b" 的顶层键, 不进入嵌套对象. 第 i 个结果与 Get(json, Escape(keys[i])) 逐字段一致 (Type/Raw/Str/Num/Index/Indexes):
- JSON 中重复的键取首次出现的值; keys 内的重复键共享同一结果.
- JSON 键含转义时先反转义再比较, 与 Get 一致.
- 与 Get 一样不校验 JSON 合法性; 畸形输入不会 panic, 结果与逐键 Get 相同.
与对每个键分别调用 Get 相比, 本函数只扫描一次, 全部命中后提前结束; 有键不存在时扫到对象末尾. 只查单个键时没有收益, 应直接用 Get.
返回值长度等于 len(keys). cap(dst) >= len(keys) 时复用 dst 的底层数组并先清零, 否则新分配. 结果与 Get 一样引用 json 的内存. 调用方用 unsafe 方式把 []byte 转成 json 时 (如 utils.B2S), 结果用完之前该字节切片不得被修改或归还缓冲池, 结果也不得交给异步消费者或长期保存.
以下情况逐键回退到 Get(json, Escape(k)), 结果仍一致, 但不再是单遍扫描, Escape 也可能分配:
- 键数超过 64.
- 存在空键或含 '*'、'?' 的键 (保守处理, 不在扫描中复刻路径通配的边界).
- 顶层第一个容器是数组 (Get 会把数字键解释为数组下标).
以下情况即使走单遍扫描也会分配: dst 容量不足, 命中值含转义 (Str 需要反转义), JSON 键含转义 (比较前反转义).
func Parse ¶
Parse parses the json and returns a result.
This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first.
func ParseBytes ¶
ParseBytes parses the json and returns a result. If working with bytes, this method preferred over Parse(string(data))
func (Result) All ¶ added in v1.4.3
All iterates over a json result. This works identically to ForEach, but allows modern Go loops:
for key, value := range res.All() {
fmt.Printf("%s %s\n", key, value)
}
与 ForEach 语义相同: 数组的 key 为 Number 类型的下标, 非对象/数组结果以空 key 迭代一次, 中途 break 即停止解析.
func (Result) Array ¶
Array returns back an array of values. If the result represents a null value or is non-existent, then an empty array will be returned. If the result is not a JSON array, the return value will be an array containing one result.
func (Result) Exists ¶
Exists returns true if value exists.
if gjson.Get(json, "name.last").Exists(){
println("value exists")
}
func (Result) ForEach ¶
ForEach iterates through values. If the result represents a non-existent value, then no values will be iterated. If the result is an Object, the iterator will pass the key and value of each item. If the result is an Array, the iterator will only pass the value of each item. If the result is not a JSON array or object, the iterator will pass back one value equal to the result.
func (Result) Get ¶
Get searches result for the specified path. The result should be a JSON array or object.
func (Result) Keys ¶ added in v1.4.3
Keys iterates over a json result. This works identically to ForEach, but allows modern Go loops:
for key := range res.Keys() {
fmt.Printf("%s\n", key)
}
对象返回键名, 数组返回 Number 类型的下标.
func (Result) Less ¶
Less return true if a token is less than another token. The caseSensitive parameter is used when the tokens are Strings. The order when comparing two different type is:
Null < False < Number < String < True < JSON
func (Result) Map ¶
Map returns back a map of values. The result should be a JSON object. If the result is not a JSON object, the return value will be an empty map.
func (Result) Path ¶
Path returns the original GJSON path for a Result where the Result came from a simple path that returns a single value, like:
gjson.Get(json, "friends.#(last=Murphy)")
返回普通 Go 路径字符串, 例如:
"friends.0"
The param 'json' must be the original JSON used when calling Get.
Returns an empty string if the paths cannot be determined, which can happen when the Result came from a path that contained a multipath, modifier, or a nested query.
func (Result) Paths ¶
Paths returns the original GJSON paths for a Result where the Result came from a simple query path that returns an array, like:
gjson.Get(json, "friends.#.first")
返回普通 Go 字符串切片形式的路径集合, 例如:
[]string{"friends.0.first", "friends.1.first", "friends.2.first"}
The param 'json' must be the original JSON used when calling Get.
缺少结果索引或结果数量与索引数量不一致时返回 nil; 单项无法还原时, 对应元素为空字符串. 包含多路径, 修饰符或嵌套查询的结果可能无法还原路径.