github.com/gogf/gf/v2@v2.7.4/encoding/gjson/gjson_z_example_new_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 12 "github.com/gogf/gf/v2/encoding/gjson" 13 ) 14 15 func ExampleNew() { 16 jsonContent := `{"name":"john", "score":"100"}` 17 j := gjson.New(jsonContent) 18 fmt.Println(j.Get("name")) 19 fmt.Println(j.Get("score")) 20 21 // Output: 22 // john 23 // 100 24 } 25 26 func ExampleNewWithTag() { 27 type Me struct { 28 Name string `tag:"name"` 29 Score int `tag:"score"` 30 Title string 31 } 32 me := Me{ 33 Name: "john", 34 Score: 100, 35 Title: "engineer", 36 } 37 j := gjson.NewWithTag(me, "tag", true) 38 fmt.Println(j.Get("name")) 39 fmt.Println(j.Get("score")) 40 fmt.Println(j.Get("Title")) 41 42 // Output: 43 // john 44 // 100 45 // engineer 46 } 47 48 func ExampleNewWithOptions() { 49 type Me struct { 50 Name string `tag:"name"` 51 Score int `tag:"score"` 52 Title string 53 } 54 me := Me{ 55 Name: "john", 56 Score: 100, 57 Title: "engineer", 58 } 59 60 j := gjson.NewWithOptions(me, gjson.Options{ 61 Tags: "tag", 62 }) 63 fmt.Println(j.Get("name")) 64 fmt.Println(j.Get("score")) 65 fmt.Println(j.Get("Title")) 66 67 // Output: 68 // john 69 // 100 70 // engineer 71 } 72 73 func ExampleNewWithOptions_UTF8BOM() { 74 jsonContent := `{"name":"john", "score":"100"}` 75 76 content := make([]byte, 3, len(jsonContent)+3) 77 content[0] = 0xEF 78 content[1] = 0xBB 79 content[2] = 0xBF 80 content = append(content, jsonContent...) 81 82 j := gjson.NewWithOptions(content, gjson.Options{ 83 Tags: "tag", 84 }) 85 fmt.Println(j.Get("name")) 86 fmt.Println(j.Get("score")) 87 88 // Output: 89 // john 90 // 100 91 } 92 93 func ExampleNew_Xml() { 94 jsonContent := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>` 95 j := gjson.New(jsonContent) 96 // Note that there's root node in the XML content. 97 fmt.Println(j.Get("doc.name")) 98 fmt.Println(j.Get("doc.score")) 99 // Output: 100 // john 101 // 100 102 } 103 104 func ExampleNew_Struct() { 105 type Me struct { 106 Name string `json:"name"` 107 Score int `json:"score"` 108 } 109 me := Me{ 110 Name: "john", 111 Score: 100, 112 } 113 j := gjson.New(me) 114 fmt.Println(j.Get("name")) 115 fmt.Println(j.Get("score")) 116 // Output: 117 // john 118 // 100 119 }