Golang一日一库之gjson
官网
一 简介
gjson实际上是get + json的缩写,用于读取 JSON 串
二 使用
1.安装
go get github.com/tidwall/gjson
2.使用
package main import ( "fmt" "github.com/tidwall/gjson" ) func main() { json := `{"name":{"first":"li","last":"dj"},"age":18}` lastName := gjson.Get(json, "name.last") fmt.Println("last name:", lastName.String()) age := gjson.Get(json, "age") fmt.Println("age:", age.Int()) }
只需要传入 JSON 串和要读取的键路径即可。注意一点细节,因为gjson.Get()函数实际上返回的是gjson.Result类型,我们要调用其相应的方法进行转换对应的类型。如上面的String()和Int()方法。
如果是直接打印输出,其实可以省略String(),fmt包的大部分函数都可以对实现fmt.Stringer接口的类型调用String()方法。
3. 遍历
gjson.Get()方法返回一个gjson.Result类型的对象,json.Result提供了ForEach()方法用于遍历。该方法接受一个类型为func (key, value gjson.Result) bool的回调函数。遍历对象时key和value分别为对象的键和值;遍历数组时,value为数组元素,key为空(不是索引)。回调返回false时,遍历停止。
const json = ` { "name":"dj", "age":18, "pets": ["cat", "dog"], "contact": { "phone": "123456789", "email": "dj@example.com" } }` func main() { pets := gjson.Get(json, "pets") pets.ForEach(func(_, pet gjson.Result) bool { fmt.Println(pet) return true }) contact := gjson.Get(json, "contact") contact.ForEach(func(key, value gjson.Result) bool { fmt.Println(key, value) return true }) }
4.一次性获得多个值
调用gjson.Get()一次只能读取一个值,多次调用又比较麻烦,gjson提供了GetMany()可以一次读取多个值,返回一个数组[]gjson.Result。
const json = ` { "name":"dj", "age":18, "pets": ["cat", "dog"], "contact": { "phone": "123456789", "email": "dj@example.com" } }` func main() { results := gjson.GetMany(json, "name", "age", "pets.#", "contact.phone") for _, result := range results { fmt.Println(result) } }
本文发表于博客园《始識的技术笔记》,作者为 zichliang(hybpjx/始識)
作者博客:https://www.cnblogs.com/zichliang
本文地址:https://www.cnblogs.com/zichliang/p/18148751
本文原创授权为:署名 - 非商业性使用 - 禁止演绎,协议普通文本 | 协议法律文本
作者博客:https://www.cnblogs.com/zichliang
本文地址:https://www.cnblogs.com/zichliang/p/18148751
本文原创授权为:署名 - 非商业性使用 - 禁止演绎,协议普通文本 | 协议法律文本
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!