github.com/gogf/gf@v1.16.9/encoding/gjson/gjson_z_example_pattern_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gjson_test 8 9 import ( 10 "fmt" 11 "github.com/gogf/gf/encoding/gjson" 12 ) 13 14 func Example_patternGet() { 15 data := 16 `{ 17 "users" : { 18 "count" : 2, 19 "list" : [ 20 {"name" : "Ming", "score" : 60}, 21 {"name" : "John", "score" : 99.5} 22 ] 23 } 24 }` 25 if j, err := gjson.DecodeToJson(data); err != nil { 26 panic(err) 27 } else { 28 fmt.Println("John Score:", j.GetFloat32("users.list.1.score")) 29 } 30 // Output: 31 // John Score: 99.5 32 } 33 34 func Example_patternCustomSplitChar() { 35 data := 36 `{ 37 "users" : { 38 "count" : 2, 39 "list" : [ 40 {"name" : "Ming", "score" : 60}, 41 {"name" : "John", "score" : 99.5} 42 ] 43 } 44 }` 45 if j, err := gjson.DecodeToJson(data); err != nil { 46 panic(err) 47 } else { 48 j.SetSplitChar('#') 49 fmt.Println("John Score:", j.GetFloat32("users#list#1#score")) 50 } 51 // Output: 52 // John Score: 99.5 53 } 54 55 func Example_patternViolenceCheck() { 56 data := 57 `{ 58 "users" : { 59 "count" : 100 60 }, 61 "users.count" : 101 62 }` 63 if j, err := gjson.DecodeToJson(data); err != nil { 64 panic(err) 65 } else { 66 j.SetViolenceCheck(true) 67 fmt.Println("Users Count:", j.GetInt("users.count")) 68 } 69 // Output: 70 // Users Count: 101 71 } 72 73 func Example_mapSliceChange() { 74 jsonContent := `{"map":{"key":"value"}, "slice":[59,90]}` 75 j, _ := gjson.LoadJson(jsonContent) 76 m := j.GetMap("map") 77 fmt.Println(m) 78 79 // Change the key-value pair. 80 m["key"] = "john" 81 82 // It changes the underlying key-value pair. 83 fmt.Println(j.GetMap("map")) 84 85 s := j.GetArray("slice") 86 fmt.Println(s) 87 88 // Change the value of specified index. 89 s[0] = 100 90 91 // It changes the underlying slice. 92 fmt.Println(j.GetArray("slice")) 93 94 // output: 95 // map[key:value] 96 // map[key:john] 97 // [59 90] 98 // [100 90] 99 }