百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
S

sjson

> 编程语言
开源

在Go中非常快速地设置JSON值

2.7K stars0 点赞2 次浏览
访问官网GitHub

工具介绍

在Go中非常快速地设置JSON值


快速设置 JSON 值

SJSON 是一个 Go 包,提供了一种非常快速且简单的方式来设置 JSON 文档中的值。 如需快速检索 JSON 值,请查看 GJSON。

如需命令行界面,请查看 JJ。

快速开始

安装

要开始使用 SJSON,请安装 Go 并运行 go get:

bash
$ go get -u github.com/tidwall/sjson

这将获取该库。

设置一个值

设置设置指定路径的值。 路径使用点语法表示,例如“name.last”或“age”。 此函数要求 JSON 格式正确且已验证。 无效的 JSON 不会引发 panic,但可能会返回意外结果。 无效的路径可能会返回错误。

go
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)
}

这将打印:

json
{"name":{"first":"Janet","last":"Anderson"},"age":47}

Path syntax

路径是由点分隔的一系列键。 点和冒号字符可以用 \ 进行转义。

json
{
  "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

通常数字键用于修改数组,但通过使用冒号字符可以强制使用数字对象键:

json
{
  "users":{
    "2313":{"name":"Sara"},
    "7839":{"name":"Andy"}
  }
}

冒号路径看起来像:

"users.:2313.name"    >> "Sara"

支持的类型

几乎任何类型都支持

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Gojson

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言