2020-03-21 19:31:58 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
|
|
//
|
|
|
|
// 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"
|
|
|
|
"github.com/gogf/gf/encoding/gjson"
|
|
|
|
)
|
|
|
|
|
2020-03-22 12:49:46 +08:00
|
|
|
func Example_newFromJson() {
|
2020-03-21 19:31:58 +08:00
|
|
|
jsonContent := `{"name":"john", "score":"100"}`
|
|
|
|
j := gjson.New(jsonContent)
|
|
|
|
fmt.Println(j.Get("name"))
|
|
|
|
fmt.Println(j.Get("score"))
|
|
|
|
// Output:
|
|
|
|
// john
|
|
|
|
// 100
|
|
|
|
}
|
|
|
|
|
2020-03-22 12:49:46 +08:00
|
|
|
func Example_newFromXml() {
|
2020-03-21 19:31:58 +08:00
|
|
|
jsonContent := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>`
|
|
|
|
j := gjson.New(jsonContent)
|
2020-03-21 21:32:02 +08:00
|
|
|
// Note that there's root node in the XML content.
|
2020-03-21 19:31:58 +08:00
|
|
|
fmt.Println(j.Get("doc.name"))
|
|
|
|
fmt.Println(j.Get("doc.score"))
|
|
|
|
// Output:
|
|
|
|
// john
|
|
|
|
// 100
|
|
|
|
}
|
|
|
|
|
2020-03-22 12:49:46 +08:00
|
|
|
func Example_newFromStruct() {
|
2020-03-21 19:31:58 +08:00
|
|
|
type Me struct {
|
|
|
|
Name string `json:"name"`
|
|
|
|
Score int `json:"score"`
|
|
|
|
}
|
|
|
|
me := Me{
|
|
|
|
Name: "john",
|
|
|
|
Score: 100,
|
|
|
|
}
|
|
|
|
j := gjson.New(me)
|
|
|
|
fmt.Println(j.Get("name"))
|
|
|
|
fmt.Println(j.Get("score"))
|
|
|
|
// Output:
|
|
|
|
// john
|
|
|
|
// 100
|
|
|
|
}
|
|
|
|
|
2020-03-22 12:49:46 +08:00
|
|
|
func Example_newFromStructWithTag() {
|
2020-03-21 19:31:58 +08:00
|
|
|
type Me struct {
|
|
|
|
Name string `tag:"name"`
|
|
|
|
Score int `tag:"score"`
|
|
|
|
Title string
|
|
|
|
}
|
|
|
|
me := Me{
|
|
|
|
Name: "john",
|
|
|
|
Score: 100,
|
|
|
|
Title: "engineer",
|
|
|
|
}
|
2020-03-21 21:32:02 +08:00
|
|
|
// The parameter <tags> specifies custom priority tags for struct conversion to map,
|
|
|
|
// multiple tags joined with char ','.
|
2020-03-21 19:31:58 +08:00
|
|
|
j := gjson.NewWithTag(me, "tag")
|
|
|
|
fmt.Println(j.Get("name"))
|
|
|
|
fmt.Println(j.Get("score"))
|
|
|
|
fmt.Println(j.Get("Title"))
|
|
|
|
// Output:
|
|
|
|
// john
|
|
|
|
// 100
|
|
|
|
// engineer
|
|
|
|
}
|