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