gjson

package
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT, MIT Imports: 14 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gjson

源自 tidwall/gjson v1.20.3 (该版唯一的代码改动 parseUint 未采纳, 见下表), 包路径改为 github.com/fufuok/pkg/xjson/gjson, 依赖本仓库的 xjson/match 与 xjson/pretty.

对上游的修正

以下修正在同步上游时必须保留, 每项都有回归测试.

位置 上游问题 本地修正 回归测试
parseUint v1.20.2 用 next < n 判断溢出, 漏掉乘 10 回绕后仍大于旧值的情况, 如 25000000000000000000 的 Int()/Uint() 得到 6553255926290448384. v1.20.3 (Issue 404) 改为: 20 字节输入按字典序与 "18446744073709551615" 比较, 大于即返回最大值, 且不检查是否全为数字. 于是 "2026-11-14T08:00:00Z"、"hello world 12345678"、"2.000000000000000000" 等 20 字节字符串的 Int()/Uint() 都得到类型最大值 不同步 v1.20.3 的 parseUint, 保留本地实现: 乘加前与 MaxUint64/10 比较, 所有溢出都饱和为最大值, 含非数字字符即判为非整数 TestIntOverflowWrapMiss, TestParseUintNotLexical; 上游 TestIssue404 已迁移并通过
f2i, f2u, safeInt NaN 直接转换为整数, 结果随 CPU 架构不同. amd64 上 "NaN" 的 Int() 为 MinInt64 NaN 统一返回 0 TestIntStringFallback
Valid, ValidBytes 递归校验没有深度上限, 约 600 万层 [ (6MB 输入) 即耗尽 1GB 栈, 进程直接退出, 无法 recover 嵌套超过 10000 层返回 false, 与 encoding/json.Valid 一致 TestValidNestingDepth
自定义修饰符表 (AddModifier/getModifier) v1.20.0 起用 sync.RWMutex 保护. 以 @ 开头的普通键 (如 ES 日志的 @timestamp) 每次查询都会先查修饰符表并加读锁, 16 核并发查询时约 26ns, v1.4.2 为 8.6ns 写时复制: atomic.Pointer 无锁读取, AddModifier 复制整表后原子替换. 注册仍可与查询并发 TestUserModifierCopyOnWrite, TestAddModifierSafety, BenchmarkAtKeyParallel
Int()/Uint() 字符串回退 v1.19.1 起整数解析失败后无条件调用 strconv.ParseFloat, 其错误对象会复制整个输入: ""、"N/A"、"null" 每次 1~2 次分配 (约 3ns 变为 50ns), 4KB 文本每次复制 4KB. 另外 ErrRange 也被当作失败, 字符串 "1e400" 得 0, 而数字 1e400 得 MaxInt64 先按字符集、符号位置、小数点个数等必要条件排除不可能是数值的串 (含日期、时间戳、IP、版本号、UUID 这类以数字开头的字段), 不再分配; 超出 float64 范围按 ±Inf 饱和, 与数字类型一致 TestIntStringNoAlloc, TestIntStringRange, TestMayParseFloat
数组下标 (parseArray) int(n) 在 32 位平台截断, GOARCH=386 下 Get("[10,20,30]", "4294967296") 命中首个元素 超出 int 的下标视为不命中 TestHugeIndexNoWrap (32 位需 GOARCH=386 go test 复现)
查询单匹配分支 (procQuery) #(...) 单匹配后再取多结果 (如 a.#(b==1).c.#.d、JSON Lines ..#(id==3).t.#.v) 时, Indexes 相对匹配元素而非原文, Paths 得到 [a.3] 这类错误路径, sjson 据此写到第 1 个元素甚至字符串内部. 上游只在 #(...)# 分支加了元素偏移 单匹配分支同样加上匹配元素的偏移 TestQueryFirstMatchIndexes
结果偏移 (Index/Indexes) 偏移在多处并不指向原文, Paths 随之出错, sjson 据此写到别处: 管道之后 Index 清零但保留相对子值的 Indexes ({"xy":1,"a":[{"b":1}]} 的 a|#.b 得 [6]、Paths 为 [xy]); #. 对字符串等标量元素以 0 为基准 ([ 1,"[1]"] 的 #.0 得 [2], 指向第一个元素); 修饰符、静态值、子选择器、嵌套多结果等新拼出的值, #./#(...)# 记为父元素偏移, Result.Get 加上父值偏移 偏移只按内存同源给出 (offsetIn): 结果切片自原文时给真实位置, 否则单结果为 0、多结果整体不给 Indexes (部分元素无法定位也不给, 避免错位). 管道右侧换算回原文 (a|#.b 得 [18]、Paths 为 [a.0.b], 单结果给出真实 Index); 子选择器之后不给 Indexes. 落在字符串字面量内部的切片也是真实位置, 由使用方判断. 三方差分 30 万条中 841 条字段、787 条 Path(s) 与上游不同, 逐条核实新偏移处即元素原文 TestIndexesProvenance, TestAlogStringElementIndex

本地保留

  • 非法 UTF-8 在 AppendJSONString 等编码路径输出 \ufffd 转义. 上游 v1.19.1 起改为原样写入 U+FFFD 字节, 两种写法都是合法 JSON, 反序列化结果相同. 本地保持历史输出, 测试中对比 Go 标准库时只接受这一处差异.

本地扩展

上游没有以下 API, 同步上游时保留. 实现单独放在 manykeys.go, 不改动任何上游函数.

API 用途 等价对照与约束 回归测试
GetManyKeys(json, keys, dst) 一次扫描顶层对象取出多个字面量键, 全部命中即停止 第 i 个结果与 Get(json, Escape(keys[i])) 逐字段一致. 键不解析路径语法. dst 容量够时复用, 结果切片不分配 (值含转义时解码 Str 仍会分配). 键数超过 64、存在空键或含 */? 的键、顶层是数组时逐键回退到 Get TestGetManyKeysOracle 随机等价, FuzzGetManyKeys, TestGetManyKeysAllocs

GetManyKeys 的键解析和未命中分支逐行复刻 parseObject 在单段非通配路径下的分支, 命中分支拆到 manyKeysParseValue; 同步上游 parseObject 的改动时必须同时复核这两个函数.

BenchmarkGetManyKeys (2026-11-14, Xeon E5-2667 v2 虚拟机, Go 1.27.2, 绑定单核 8 轮交错, 与逐键 Get 对比): 单键且命中靠前时约多 15ns 固定开销, 靠后或缺失时持平; 2 个键持平至快 56%; 4 个键及以上快 13%~96% (4 个键全部靠前时收益最小); 快速路径 0 分配. 只查一个键时继续用 Get. 用请求键的 (长度, 首尾字节) 指纹预过滤 JSON 键, 并把命中分支移出热循环, 使单键扫描成本与 Get 持平 (调整前约慢 20%).

已移除的 API

上游 v1.20.0 已让以下全局变量失效, 本地直接删除, 不保留兼容. 应用升级时编译报错即需迁移:

已删除 替代方式
DisableEscapeHTML = true gjson.SetEscapeHTML(false), 并发安全, 可在运行期切换
DisableModifiers = true 编译参数 -ldflags="-X 'github.com/fufuok/pkg/xjson/gjson.disableModifiers=true'"

另外, AddModifier 不能再覆盖 @pretty、@this 等内置修饰符, 同名注册会被忽略.

已知问题 (上游同样存在, 暂不修改)

2026-11 审查确认以下问题, 修复面大或没有现实触发路径, 暂不修改. 使用时请避开:

  • Value() 和 @pretty 的耗时与嵌套深度成平方关系, @pretty 还会递归到栈溢出. 不要对不可信输入调用它们. 不可信输入先用 Valid 或 pkg/json.Valid 校验, 再按路径 Get.
  • 对字符串结果继续取值时会扫描字符串内容. 例如 Get({"s":"[1,2]"}, "s|0") 得到 1. 需要数组时先检查 IsArray(). 本地 sjson 写入时已不再经由字符串取值 (见 sjson/README.md).
  • 路径段中同时含未转义的通配符时, 转义的 \*、\? 也按通配符匹配, 如 a\*b* 能匹配键 axbc. 只含转义通配符时按字面量匹配, Escape 生成的路径不受影响.
  • #(...)#.x|pipe 在没有元素匹配时会丢掉管道后的部分.
  • #. 之后的键和查询之后的剩余路径先经 splitPossiblePipe 切管道. 它只保护前面带 . 的 .#( 查询体, 括号只按同类计数, 开头的 #( 不受保护, 查询值里的 | 可能被切成管道 (如 #.#(b|#(v)#)). parseArrayPath 也不处理转义, 查询之后的 \| 同样是管道. 这类路径的取值可能与直觉不同, 但偏移按内存同源给出, 不会错位.
  • 段首的 #(...) 只在当前值是数组时是查询. 当前值是对象时整段按普通键路径解析, 查询体里的 |、. 会切出管道或下一段, 如对象有键 #(b==" 时 #(b=="|#.c") 先取该键再经管道取 #.c").
  • ! 静态值后接管道或含 ] 的字符串时解析错误.
  • 通配路径匹配超长键时耗时可达秒级. 例如 5 万字节的键匹配 *a*b*. 不要把外部输入当作 gjson 路径.
  • 对数组调用 Map() 返回 nil map.

免复制查询

GetBytes、GetManyBytes 会把命中的 Raw/Str 复制成独立字符串, 结果可以长期保存. 只在当前调用内同步使用结果时, 可以借用原文, 不再复制:

复制版本 借用写法 说明
GetBytes(b, path) Get(utils.B2S(b), path) 结果引用 b; 值含转义时 Str 仍会分配
GetManyBytes(b, paths...) 循环 Get(utils.B2S(b), p) 写入调用方的定长数组 GetMany 仍会分配结果切片
GetBytes(b, path).Exists() Get(utils.B2S(b), path).Exists() 命中对象或数组时, 复制版本会复制整段 Raw

借用的约束: 结果用完之前, b 不能被修改、归还缓冲池或交给其他协程改写; 结果也不能交给异步消费者或长期缓存.

GetMany/GetManyBytes 对每个路径各扫描一次文档, 并不是一次扫描取多个字段. 只取顶层字面量键时可用本地扩展 GetManyKeys 单遍扫描, 结果同样借用输入.

同步上游

用 go mod download -json github.com/tidwall/gjson@<version> 取得源码, 逐版本对比后合入功能改动. 保留导入路径、中文注释和本文件列出的差异, 迁移上游新增测试, 并更新 xjson/README.md 的版本表.

Documentation

Overview

Package gjson provides searching for json strings.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddModifier

func AddModifier(name string, fn func(json, arg string) string)

AddModifier binds a custom modifier command to the GJSON syntax. Provide the name of the modifier without the '@' prefix. 内置修饰符 (如 pretty/this/valid) 不可覆盖, 同名注册会被忽略. 可与查询并发调用; 同名自定义修饰符以最后一次注册为准. 每次注册都复制整张自定义表 (写时复制), 适合启动期或低频注册, 不宜在热路径反复调用.

func AppendJSONString

func AppendJSONString(dst []byte, s string) []byte

AppendJSONString is a convenience function that converts the provided string to a valid JSON string and appends it to dst.

func Escape

func Escape(comp string) string

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

func ForEachLine(json string, iterator func(line Result) bool)

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

func ModifierExists(name string, fn func(json, arg string) string) bool

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

func Valid(json string) bool

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

func ValidBytes(json []byte) bool

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

func Get(json, path string) Result

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

func GetBytes(json []byte, path string) Result

GetBytes searches json for the specified path. If working with bytes, this method preferred over Get(string(data), path)

func GetMany

func GetMany(json string, path ...string) []Result

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

func GetManyBytes(json []byte, path ...string) []Result

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

func GetManyKeys(json string, keys []string, dst []Result) []Result

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

func Parse(json string) Result

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

func ParseBytes(json []byte) Result

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

func (t Result) All() iter.Seq2[Result, Result]

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

func (t Result) Array() []Result

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) Bool

func (t Result) Bool() bool

Bool 返回该结果的布尔表示.

func (Result) Exists

func (t Result) Exists() bool

Exists returns true if value exists.

 if gjson.Get(json, "name.last").Exists(){
		println("value exists")
 }

func (Result) Float

func (t Result) Float() float64

Float 返回该结果的 float64 表示.

func (Result) ForEach

func (t Result) ForEach(iterator func(key, value Result) bool)

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

func (t Result) Get(path string) Result

Get searches result for the specified path. The result should be a JSON array or object.

func (Result) Int

func (t Result) Int() int64

Int returns an integer representation.

func (Result) IsArray

func (t Result) IsArray() bool

IsArray returns true if the result value is a JSON array.

func (Result) IsBool

func (t Result) IsBool() bool

IsBool returns true if the result value is a JSON boolean.

func (Result) IsObject

func (t Result) IsObject() bool

IsObject returns true if the result value is a JSON object.

func (Result) Keys added in v1.4.3

func (t Result) Keys() iter.Seq[Result]

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

func (t Result) Less(token Result, caseSensitive bool) bool

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

func (t Result) Map() map[string]Result

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

func (t Result) Path(json string) string

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

func (t Result) Paths(json string) []string

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; 单项无法还原时, 对应元素为空字符串. 包含多路径, 修饰符或嵌套查询的结果可能无法还原路径.

func (Result) String

func (t Result) String() string

String returns a string representation of the value.

func (Result) Time

func (t Result) Time() time.Time

Time returns a time.Time representation.

func (Result) Uint

func (t Result) Uint() uint64

Uint returns an unsigned integer representation.

func (Result) Value

func (t Result) Value() any

Value returns one of these types:

bool, for JSON booleans
float64, for JSON numbers
Number, for JSON numbers
string, for JSON string literals
nil, for JSON null
map[string]interface{}, for JSON objects
[]interface{}, for JSON arrays

func (Result) Values added in v1.4.3

func (t Result) Values() iter.Seq[Result]

Values iterates over a json result. This works identically to ForEach, but allows modern Go loops:

for value := range res.Values() {
	fmt.Printf("%s\n", value)
}

适合只关心数组元素或对象值的场景, 不生成中间切片.

type Type

type Type int

Type is Result type

const (
	// Null is a null json value
	Null Type = iota
	// False is a json false boolean
	False
	// Number is json number
	Number
	// String is a json string
	String
	// True is a json true boolean
	True
	// JSON is a raw block of JSON
	JSON
)

func (Type) String

func (t Type) String() string

String returns a string representation of the type.

Jump to

Keyboard shortcuts

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