在Go中非常快速地设置JSON值
快速设置 JSON 值
SJSON 是一个 Go 包,提供了一种非常快速且简单的方式来设置 JSON 文档中的值。 如需快速检索 JSON 值,请查看 GJSON。
如需命令行界面,请查看 JJ。
要开始使用 SJSON,请安装 Go 并运行 go get:
$ go get -u github.com/tidwall/sjson这将获取该库。
设置设置指定路径的值。 路径使用点语法表示,例如“name.last”或“age”。 此函数要求 JSON 格式正确且已验证。 无效的 JSON 不会引发 panic,但可能会返回意外结果。 无效的路径可能会返回错误。
package main
import "github.com/tidwall/sjson"
const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
func main() {
value, _ := sjson.Set(json, "name.last", "Anderson")
println(value)
}这将打印:
{"name":{"first":"Janet","last":"Anderson"},"age":47}路径是由点分隔的一系列键。
点和冒号字符可以用 \ 进行转义。
{
"name": {"first": "Tom", "last": "Anderson"},
"age":37,
"children": ["Sara","Alex","Jack"],
"fav.movie": "Deer Hunter",
"friends": [
{"first": "James", "last": "Murphy"},
{"first": "Roger", "last": "Craig"}
]
}"name.last" >> "Anderson"
"age" >> 37
"children.1" >> "Alex"
"friends.1.last" >> "Craig"-1 键可用于向现有数组追加值:
"children.-1" >> appends a new value to the end of the children array通常数字键用于修改数组,但通过使用冒号字符可以强制使用数字对象键:
{
"users":{
"2313":{"name":"Sara"},
"7839":{"name":"Andy"}
}
}冒号路径看起来像:
"users.:2313.name" >> "Sara"几乎任何类型都支持
暂无开放 Issues,或尚未同步最近议题。