github.com/wangyougui/gf/v2@v2.6.5/encoding/gjson/gjson_z_example_dataset_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/wangyougui/gf.
     6  
     7  package gjson_test
     8  
     9  import (
    10  	"fmt"
    11  
    12  	"github.com/wangyougui/gf/v2/encoding/gjson"
    13  )
    14  
    15  func ExampleJson_Set_DataSetCreate1() {
    16  	j := gjson.New(nil)
    17  	j.Set("name", "John")
    18  	j.Set("score", 99.5)
    19  	fmt.Printf(
    20  		"Name: %s, Score: %v\n",
    21  		j.Get("name").String(),
    22  		j.Get("score").Float32(),
    23  	)
    24  	fmt.Println(j.MustToJsonString())
    25  
    26  	// Output:
    27  	// Name: John, Score: 99.5
    28  	// {"name":"John","score":99.5}
    29  }
    30  
    31  func ExampleJson_Set_DataSetCreate2() {
    32  	j := gjson.New(nil)
    33  	for i := 0; i < 5; i++ {
    34  		j.Set(fmt.Sprintf(`%d.id`, i), i)
    35  		j.Set(fmt.Sprintf(`%d.name`, i), fmt.Sprintf(`student-%d`, i))
    36  	}
    37  	fmt.Println(j.MustToJsonString())
    38  
    39  	// Output:
    40  	// [{"id":0,"name":"student-0"},{"id":1,"name":"student-1"},{"id":2,"name":"student-2"},{"id":3,"name":"student-3"},{"id":4,"name":"student-4"}]
    41  }
    42  
    43  func ExampleJson_DataSetRuntimeEdit() {
    44  	data :=
    45  		`{
    46          "users" : {
    47              "count" : 2,
    48              "list"  : [
    49                  {"name" : "Ming", "score" : 60},
    50                  {"name" : "John", "score" : 59}
    51              ]
    52          }
    53      }`
    54  	if j, err := gjson.DecodeToJson(data); err != nil {
    55  		panic(err)
    56  	} else {
    57  		j.Set("users.list.1.score", 100)
    58  		fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
    59  		fmt.Println(j.MustToJsonString())
    60  	}
    61  	// Output:
    62  	// John Score: 100
    63  	// {"users":{"count":2,"list":[{"name":"Ming","score":60},{"name":"John","score":100}]}}
    64  }