gf/encoding/gjson/gjson_z_example_pattern_test.go

100 lines
2.1 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
2020-03-21 21:32:02 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gjson_test
import (
"fmt"
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/encoding/gjson"
2020-03-21 21:32:02 +08:00
)
2020-03-22 12:49:46 +08:00
func Example_patternGet() {
2020-03-21 21:32:02 +08:00
data :=
`{
"users" : {
"count" : 2,
"list" : [
{"name" : "Ming", "score" : 60},
{"name" : "John", "score" : 99.5}
]
}
}`
if j, err := gjson.DecodeToJson(data); err != nil {
panic(err)
} else {
fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
2020-03-21 21:32:02 +08:00
}
// Output:
// John Score: 99.5
}
2020-03-22 12:49:46 +08:00
func Example_patternCustomSplitChar() {
2020-03-21 21:32:02 +08:00
data :=
`{
"users" : {
"count" : 2,
"list" : [
{"name" : "Ming", "score" : 60},
{"name" : "John", "score" : 99.5}
]
}
}`
if j, err := gjson.DecodeToJson(data); err != nil {
panic(err)
} else {
j.SetSplitChar('#')
fmt.Println("John Score:", j.Get("users#list#1#score").Float32())
2020-03-21 21:32:02 +08:00
}
// Output:
// John Score: 99.5
}
2020-03-22 12:49:46 +08:00
func Example_patternViolenceCheck() {
2020-03-21 21:32:02 +08:00
data :=
`{
"users" : {
"count" : 100
},
"users.count" : 101
}`
if j, err := gjson.DecodeToJson(data); err != nil {
panic(err)
} else {
j.SetViolenceCheck(true)
fmt.Println("Users Count:", j.Get("users.count").Int())
2020-03-21 21:32:02 +08:00
}
// Output:
// Users Count: 101
}
2020-03-28 00:37:23 +08:00
func Example_mapSliceChange() {
jsonContent := `{"map":{"key":"value"}, "slice":[59,90]}`
j, _ := gjson.LoadJson(jsonContent)
m := j.Get("map").Map()
2020-03-28 00:37:23 +08:00
fmt.Println(m)
// Change the key-value pair.
m["key"] = "john"
// It changes the underlying key-value pair.
fmt.Println(j.Get("map").Map())
2020-03-28 00:37:23 +08:00
s := j.Get("slice").Array()
2020-03-28 00:37:23 +08:00
fmt.Println(s)
// Change the value of specified index.
s[0] = 100
// It changes the underlying slice.
fmt.Println(j.Get("slice").Array())
2020-03-28 00:37:23 +08:00
// output:
// map[key:value]
// map[key:john]
// [59 90]
// [100 90]
}