目录

前言:

JSON 解析是我们不可避免的常见问题,在 Go 语言中,我们可以借助 gjson 库来方便的进行 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...abcab?ab1/ab2ab
.aa.0a.1
.#a.#a
.\

4. json 数组遍历

gjsongjson.Get()gjson.Resultjson.ResultForEach()func (key, value gjson.Result) boolkeyvaluevaluekeyfalse
  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()
gjson.GetMany()
您可能感兴趣的文章: