温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Go语言json解析框架与gjson怎么使用

发布时间:2022-08-01 11:08:40 来源:亿速云 阅读:110 作者:iii 栏目:开发技术

本篇内容主要讲解“Go语言json解析框架与gjson怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Go语言json解析框架与gjson怎么使用”吧!

1. 快速使用

快速安装:

 go get github.com/tidwall/gjson

Get() 方法解析 json 字符串:

    json := `{"name":{"first":"uncle","last":"suta"}}`
    lastName := gjson.Get(json, "name.last")
    fmt.Println(lastName.String()) // "uncle"

通过上面的例子,我们可以看到,使用 gjson 中的 Get() 方法,我们可以轻松愉快的进行 json 解析。

2. Get() 返回的 Result 结构体

Get() 方法在解析完 json 字符串后,返回的是一个 Result 结构体,其结构如下所示:

// Result represents a json value that is returned from Get().
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
}

但是,我们解析 json 所需要的往往是基本数据类型,因此,Result 结构体本身为我们实现了如下所示的丰富的方法来进行类型转化:

String() string
Bool() bool
Int() int64
Uint() uint64
Float() float64
Time() time.Time
Array() []Result
IsObject() bool
IsArray() bool
ForEach(iterator func(key Result, value Result) bool)
Map() map[string]Result
Get(path string) Result
arrayOrMap(vc byte, valueize bool) (r arrayOrMapResult)
Exists() bool
Value() interface{}
Less(token Result, caseSensitive bool) bool
Paths(json string) []string
Path(json string) string

3. 键路径

在 gjson 中,键路径实际上是以.分隔的一系列键。

gjson支持在键中包含通配符*?*匹配任意多个字符,?匹配单个字符。 例如abc*可以匹配abc1111/abc222/abc...等以abc开头的键,ab?只能匹配ab1/ab2等以ab开头且后面只有一个字符的键。

数组使用键名 + . + 索引(索引从 0 开始)的方式读取元素,如果键a对应的值是一个数组,那么a.0读取数组的第一个元素,a.1读取第二个元素。

数组长度使用键名 + . + #获取,例如a.#返回数组a的长度。

如果键名中出现.,那么需要使用\进行转义。

4. json 数组遍历

gjson还提供了通用的遍历数组和对象的方式。gjson.Get()方法返回一个gjson.Result类型的对象,json.Result提供了ForEach()方法用于遍历。该方法接受一个类型为func (key, value gjson.Result) bool的回调函数。遍历对象时keyvalue分别为对象的键和值;遍历数组时,value为数组元素,key为空(不是索引)。回调返回false时,遍历停止:

  json := `{"list": ["a", "b", "c"]}`
  list := gjson.Get(json, "list")
  list.ForEach(func(_, element gjson.Result) bool {
    fmt.Println(element)
    return true
  })

5. 其他

gjson.Valid() 可以对 json 字符串的合法性进行校验。

gjson.GetMany() 可以一次解析多个字段。

到此,相信大家对“Go语言json解析框架与gjson怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI