The following list of commonly used methods may be updated later than new code features. For more methods and examples, please refer to the code documentation: https://pkg.go.dev/github.com/gogf/gf/v2/encoding/gjson
New
-
Description:
Newcan create aJsonobject with any type of valuedata. However, due to data access reasons,datashould be amaporslice, otherwise it is meaningless. -
Note: The
safeparameter determines whether theJsonobject is concurrent-safe, defaulting tofalse. -
Format:
func New(data interface{}, safe ...bool) *Json
- Example:
func ExampleNew() {
jsonContent := `{"name":"john", "score":"100"}`
j := gjson.New(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
NewWithTag
-
Description:
NewWithTagcan create aJsonobject with any type of valuedata. However, due to data access reasons,datashould be amaporslice, otherwise it is meaningless. -
Note: The
tgtsparameter specifies the priority of tag names when converting structs to maps, with multiple tags separated by','. -
The
safeparameter determines whether theJsonobject is concurrent-safe, defaulting tofalse. -
Format:
func NewWithTag(data interface{}, tags string, safe ...bool) *Json
- Example:
func ExampleNewWithTag() {
type Me struct {
Name string `tag:"name"`
Score int `tag:"score"`
Title string
}
me := Me{
Name: "john",
Score: 100,
Title: "engineer",
}
j := gjson.NewWithTag(me, "tag", true)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(j.Get("Title"))
// Output:
// john
// 100
// engineer
}
NewWithOptions
-
Description:
NewWithOptionscan create aJsonobject with any type of valuedata. However, due to data access reasons,datashould be amaporslice, otherwise it is meaningless. -
Format:
func NewWithOptions(data interface{}, options Options) *Json
- Example:
func ExampleNewWithOptions() {
type Me struct {
Name string `tag:"name"`
Score int `tag:"score"`
Title string
}
me := Me{
Name: "john",
Score: 100,
Title: "engineer",
}
j := gjson.NewWithOptions(me, gjson.Options{
Tags: "tag",
})
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(j.Get("Title"))
// Output:
// john
// 100
// engineer
}
func ExampleNewWithOptions_UTF8BOM() {
jsonContent := `{"name":"john", "score":"100"}`
content := make([]byte, 3, len(jsonContent)+3)
content[0] = 0xEF
content[1] = 0xBB
content[2] = 0xBF
content = append(content, jsonContent...)
j := gjson.NewWithOptions(content, gjson.Options{
Tags: "tag",
})
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
Load
-
Description:
Loadloads content from the specified filepathand creates aJsonobject from it. -
Format:
func Load(path string, safe ...bool) (*Json, error)
- Example:
func ExampleLoad() {
jsonFilePath := gtest.DataPath("json", "data1.json")
j, _ := gjson.Load(jsonFilePath)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
notExistFilePath := gtest.DataPath("json", "data2.json")
j2, _ := gjson.Load(notExistFilePath)
fmt.Println(j2.Get("name"))
// Output:
// john
// 100
}
func ExampleLoad_Xml() {
jsonFilePath := gtest.DataPath("xml", "data1.xml")
j, _ := gjson.Load(jsonFilePath)
fmt.Println(j.Get("doc.name"))
fmt.Println(j.Get("doc.score"))
}
LoadJson
-
Description:
LoadJsoncreates aJsonobject from the given content inJSONformat. -
Format:
func LoadJson(data interface{}, safe ...bool) (*Json, error)
- Example:
func ExampleLoadJson() {
jsonContent := `{"name":"john", "score":"100"}`
j, _ := gjson.LoadJson(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
LoadXml
-
Description:
LoadXmlcreates aJsonobject from the given content inXMLformat. -
Format:
func LoadXml(data interface{}, safe ...bool) (*Json, error)
- Example:
func ExampleLoadXml() {
xmlContent := `<?xml version="1.0" encoding="UTF-8"?>
<base>
<name>john</name>
<score>100</score>
</base>`
j, _ := gjson.LoadXml(xmlContent)
fmt.Println(j.Get("base.name"))
fmt.Println(j.Get("base.score"))
// Output:
// john
// 100
}
LoadIni
-
Description:
LoadInicreates aJsonobject from the given content inINIformat. -
Format:
func LoadIni(data interface{}, safe ...bool) (*Json, error)
- Example:
func ExampleLoadIni() {
iniContent := `
[base]
name = john
score = 100
`
j, _ := gjson.LoadIni(iniContent)
fmt.Println(j.Get("base.name"))
fmt.Println(j.Get("base.score"))
// Output:
// john
// 100
}
LoadYaml
-
Description:
LoadYamlcreates aJsonobject from the given content inYAMLformat. -
Format:
func LoadYaml(data interface{}, safe ...bool) (*Json, error)
- Example:
func ExampleLoadYaml() {
yamlContent :=
`base:
name: john
score: 100`
j, _ := gjson.LoadYaml(yamlContent)
fmt.Println(j.Get("base.name"))
fmt.Println(j.Get("base.score"))
// Output:
// john
// 100
}
LoadToml
-
Description:
LoadTomlcreates aJsonobject from the given content inTOMLformat. -
Format:
func LoadToml(data interface{}, safe ...bool) (*Json, error)
- Example:
func ExampleLoadToml() {
tomlContent :=
`[base]
name = "john"
score = 100`
j, _ := gjson.LoadToml(tomlContent)
fmt.Println(j.Get("base.name"))
fmt.Println(j.Get("base.score"))
// Output:
// john
// 100
}
LoadContent
-
Description:
LoadContentcreates aJsonobject based on the given content. It automatically checks the data type ofcontent, supporting content types such asJSON, XML, INI, YAML, and TOML. -
Format:
func LoadContent(data interface{}, safe ...bool) (*Json, error)
- Example:
func ExampleLoadContent() {
jsonContent := `{"name":"john", "score":"100"}`
j, _ := gjson.LoadContent(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
func ExampleLoadContent_UTF8BOM() {
jsonContent := `{"name":"john", "score":"100"}`
content := make([]byte, 3, len(jsonContent)+3)
content[0] = 0xEF
content[1] = 0xBB
content[2] = 0xBF
content = append(content, jsonContent...)
j, _ := gjson.LoadContent(content)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
func ExampleLoadContent_Xml() {
xmlContent := `<?xml version="1.0" encoding="UTF-8"?>
<base>
<name>john</name>
<score>100</score>
</base>`
x, _ := gjson.LoadContent(xmlContent)
fmt.Println(x.Get("base.name"))
fmt.Println(x.Get("base.score"))
// Output:
// john
// 100
}
LoadContentType
-
Description:
LoadContentTypecreates aJsonobject based on the given content and type. Supported content types areJson, XML, INI, YAML, and TOML. -
Format:
func LoadContentType(dataType string, data interface{}, safe ...bool) (*Json, error)
- Example:
func ExampleLoadContentType() {
jsonContent := `{"name":"john", "score":"100"}`
xmlContent := `<?xml version="1.0" encoding="UTF-8"?>
<base>
<name>john</name>
<score>100</score>
</base>`
j, _ := gjson.LoadContentType("json", jsonContent)
x, _ := gjson.LoadContentType("xml", xmlContent)
j1, _ := gjson.LoadContentType("json", "")
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(x.Get("base.name"))
fmt.Println(x.Get("base.score"))
fmt.Println(j1.Get(""))
// Output:
// john
// 100
// john
// 100
}
IsValidDataType
-
Description:
IsValidDataTypechecks if the givendataTypeis a valid content type for loading. -
Format:
func IsValidDataType(dataType string) bool
- Example:
func ExampleIsValidDataType() {
fmt.Println(gjson.IsValidDataType("json"))
fmt.Println(gjson.IsValidDataType("yml"))
fmt.Println(gjson.IsValidDataType("js"))
fmt.Println(gjson.IsValidDataType("mp4"))
fmt.Println(gjson.IsValidDataType("xsl"))
fmt.Println(gjson.IsValidDataType("txt"))
fmt.Println(gjson.IsValidDataType(""))
fmt.Println(gjson.IsValidDataType(".json"))
// Output:
// true
// true
// true
// false
// false
// false
// false
// true
}
Valid
-
Description:
Validchecks ifdatais a validJSONdata type. Thedataparameter specifies theJSONformatted data, which can be of typebytesorstring. -
Format:
func Valid(data interface{}) bool
- Example:
func ExampleValid() {
data1 := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
data2 := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]`)
fmt.Println(gjson.Valid(data1))
fmt.Println(gjson.Valid(data2))
// Output:
// true
// false
}
Marshal
-
Description:
Marshalis an alias forEncode. -
Format:
func Marshal(v interface{}) (marshaledBytes []byte, err error)
- Example:
func ExampleMarshal() {
data := map[string]interface{}{
"name": "john",
"score": 100,
}
jsonData, _ := gjson.Marshal(data)
fmt.Println(string(jsonData))
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "Guo Qiang",
Age: 18,
}
infoData, _ := gjson.Marshal(info)
fmt.Println(string(infoData))
// Output:
// {"name":"john","score":100}
// {"Name":"Guo Qiang","Age":18}
}
MarshalIndent
-
Description:
MarshalIndentis an alias forjson.MarshalIndent. -
Format:
func MarshalIndent(v interface{}, prefix, indent string) (marshaledBytes []byte, err error)
- Example:
func ExampleMarshalIndent() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
infoData, _ := gjson.MarshalIndent(info, "", "\t")
fmt.Println(string(infoData))
// Output:
// {
// "Name": "John",
// "Age": 18
// }
}
Unmarshal
-
Description:
Unmarshalis an alias forDecodeTo. -
Format:
func Unmarshal(data []byte, v interface{}) (err error)
- Example:
func ExampleUnmarshal() {
type BaseInfo struct {
Name string
Score int
}
var info BaseInfo
jsonContent := "{\"name\":\"john\",\"score\":100}"
gjson.Unmarshal([]byte(jsonContent), &info)
fmt.Printf("%+v", info)
// Output:
// {Name:john Score:100}
}
Encode
-
Description:
Encodeserializes any typevalueinto abytearray with content inJSONformat. -
Format:
func Encode(value interface{}) ([]byte, error)
- Example:
func ExampleEncode() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
infoData, _ := gjson.Encode(info)
fmt.Println(string(infoData))
// Output:
// {"Name":"John","Age":18}
}
MustEncode
-
Description:
MustEncodeperforms theEncodeoperation but willpanicif any error occurs. -
Format:
func MustEncode(value interface{}) []byte
- Example:
func ExampleMustEncode() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
infoData := gjson.MustEncode(info)
fmt.Println(string(infoData))
// Output:
// {"Name":"John","Age":18}
}
EncodeString
-
Description:
EncodeStringserializes any typevalueinto astringwith content inJSONformat. -
Format:
func EncodeString(value interface{}) (string, error)
- Example:
func ExampleEncodeString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
infoData, _ := gjson.EncodeString(info)
fmt.Println(infoData)
// Output:
// {"Name":"John","Age":18}
}
MustEncodeString
-
Description:
MustEncodeStringserializes any typevalueinto astringwith content inJSONformat but willpanicif any error occurs. -
Format:
func MustEncodeString(value interface{}) string
- Example:
func ExampleMustEncodeString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
infoData := gjson.MustEncodeString(info)
fmt.Println(infoData)
// Output:
// {"Name":"John","Age":18}
}
Decode
-
Description:
DecodedecodesdatainJSONformat tointerface{}. Thedataparameter can be[]byteorstring. -
Format:
func Decode(data interface{}, options ...Options) (interface{}, error)
- Example:
func ExampleDecode() {
jsonContent := `{"name":"john","score":100}`
info, _ := gjson.Decode([]byte(jsonContent))
fmt.Println(info)
// Output:
// map[name:john score:100]
}
DecodeTo
-
Description:
DecodeTodecodesdatainJSONformat to the specifiedinterfacetype variablev. Thedataparameter can be[]byteorstring. Thevparameter should be of pointer type. -
Format:
func DecodeTo(data interface{}, v interface{}, options ...Options) (err error)
- Example:
func ExampleDecodeTo() {
type BaseInfo struct {
Name string
Score int
}
var info BaseInfo
jsonContent := "{\"name\":\"john\",\"score\":100}"
gjson.DecodeTo([]byte(jsonContent), &info)
fmt.Printf("%+v", info)
// Output:
// {Name:john Score:100}
}
DecodeToJson
-
Description:
DecodeToJsonencodesdatainJSONformat into ajsonobject. Thedataparameter can be[]byteorstring. -
Format:
func DecodeToJson(data interface{}, options ...Options) (*Json, error)
- Example:
func ExampleDecodeToJson() {
jsonContent := `{"name":"john","score":100}"`
j, _ := gjson.DecodeToJson([]byte(jsonContent))
fmt.Println(j.Map())
// May Output:
// map[name:john score:100]
}
SetSplitChar
-
Description:
SetSplitCharsets the level delimiter for data access. -
Format:
func (j *Json) SetSplitChar(char byte)
- Example:
func ExampleJson_SetSplitChar() {
data :=
`{
"users" : {
"count" : 2,
"list" : [
{"name" : "Ming", "score" : 60},
{"name" : "John", "score" : 99.5}
]
}
}`
if j, err := gjson.DecodeToJson(data); err != nil {
panic(err)
} else {
j.SetSplitChar('#')
fmt.Println("John Score:", j.Get("users#list#1#score").Float32())
}
// Output:
// John Score: 99.5
}
SetViolenceCheck
-
Description:
SetViolenceCheckenables/disables violent check for data level access. -
Format:
func (j *Json) SetViolenceCheck(enabled bool)
- Example:
func ExampleJson_SetViolenceCheck() {
data :=
`{
"users" : {
"count" : 100
},
"users.count" : 101
}`
if j, err := gjson.DecodeToJson(data); err != nil {
fmt.Println(err)
} else {
j.SetViolenceCheck(true)
fmt.Println("Users Count:", j.Get("users.count"))
}
// Output:
// Users Count: 101
}
ToJson
-
Description:
ToJsonreturns theJSONcontent as a[]bytetype. -
Format:
func (j *Json) ToJson() ([]byte, error)
- Example:
func ExampleJson_ToJson() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonBytes, _ := j.ToJson()
fmt.Println(string(jsonBytes))
// Output:
// {"Age":18,"Name":"John"}
}
ToJsonString
-
Description:
ToJsonStringreturns theJSONcontent as astringtype. -
Format:
func (j *Json) ToJsonString() (string, error)
- Example:
func ExampleJson_ToJsonString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonStr, _ := j.ToJsonString()
fmt.Println(jsonStr)
// Output:
// {"Age":18,"Name":"John"}
}
ToJsonIndent
-
Description:
ToJsonIndentreturns the indentedJSONcontent as a[]bytetype. -
Format:
func (j *Json) ToJsonIndent() ([]byte, error)
- Example:
func ExampleJson_ToJsonIndent() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonBytes, _ := j.ToJsonIndent()
fmt.Println(string(jsonBytes))
// Output:
//{
// "Age": 18,
// "Name": "John"
//}
}
ToJsonIndentString
-
Description:
ToJsonIndentStringreturns the indentedJSONcontent as astringtype. -
Format:
func (j *Json) ToJsonIndentString() (string, error)
- Example:
func ExampleJson_ToJsonIndentString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonStr, _ := j.ToJsonIndentString()
fmt.Println(jsonStr)
// Output:
//{
// "Age": 18,
// "Name": "John"
//}
}
MustToJson
-
Description:
MustToJsonreturns theJSONcontent as a[]bytetype, and if any error occurs, it willpanic. -
Format:
func (j *Json) MustToJson() []byte
- Example:
func ExampleJson_MustToJson() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonBytes := j.MustToJson()
fmt.Println(string(jsonBytes))
// Output:
// {"Age":18,"Name":"John"}
}
MustToJsonString
-
Description:
MustToJsonStringreturns theJSONcontent as astringtype, and if any error occurs, it willpanic. -
Format:
func (j *Json) MustToJsonString() string
- Example:
func ExampleJson_MustToJsonString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonStr := j.MustToJsonString()
fmt.Println(jsonStr)
// Output:
// {"Age":18,"Name":"John"}
}
MustToJsonIndent
-
Description:
MustToJsonStringIndentreturns the indentedJSONcontent as a[]bytetype, and if any error occurs, it willpanic. -
Format:
func (j *Json) MustToJsonIndent() []byte
- Example:
func ExampleJson_MustToJsonIndent() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonBytes := j.MustToJsonIndent()
fmt.Println(string(jsonBytes))
// Output:
//{
// "Age": 18,
// "Name": "John"
//}
}
MustToJsonIndentString
-
Description:
MustToJsonStringIndentreturns the indentedJSONcontent as astringtype, and if any error occurs, it willpanic. -
Format:
func (j *Json) MustToJsonIndentString() string
- Example:
func ExampleJson_MustToJsonIndentString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonStr := j.MustToJsonIndentString()
fmt.Println(jsonStr)
// Output:
//{
// "Age": 18,
// "Name": "John"
//}
}
ToXml
-
Description:
ToXmlreturns content inXMLformat as a[]bytetype. -
Format:
func (j *Json) ToXml(rootTag ...string) ([]byte, error)
- Example:
func ExampleJson_ToXml() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlBytes, _ := j.ToXml()
fmt.Println(string(xmlBytes))
// Output:
// <doc><Age>18</Age><Name>John</Name></doc>
}
ToXmlString
-
Description:
ToXmlStringreturns content inXMLformat as astringtype. -
Format:
func (j *Json) ToXmlString(rootTag ...string) (string, error)
- Example:
func ExampleJson_ToXmlString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlStr, _ := j.ToXmlString()
fmt.Println(string(xmlStr))
// Output:
// <doc><Age>18</Age><Name>John</Name></doc>
}
ToXmlIndent
-
Description:
ToXmlIndentreturns indented content inXMLformat as a[]bytetype. -
Format:
func (j *Json) ToXmlIndent(rootTag ...string) ([]byte, error)
- Example:
func ExampleJson_ToXmlIndent() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlBytes, _ := j.ToXmlIndent()
fmt.Println(string(xmlBytes))
// Output:
//<doc>
// <Age>18</Age>
// <Name>John</Name>
//</doc>
}
ToXmlIndentString
-
Description:
ToXmlIndentStringreturns indented content inXMLformat as astringtype. -
Format:
func (j *Json) ToXmlIndentString(rootTag ...string) (string, error)
- Example:
func ExampleJson_ToXmlIndentString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlStr, _ := j.ToXmlIndentString()
fmt.Println(string(xmlStr))
// Output:
//<doc>
// <Age>18</Age>
// <Name>John</Name>
//</doc>
}
MustToXml
-
Description:
MustToXmlreturns content inXMLformat as a[]bytetype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToXml(rootTag ...string) []byte
- Example:
func ExampleJson_MustToXml() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlBytes := j.MustToXml()
fmt.Println(string(xmlBytes))
// Output:
// <doc><Age>18</Age><Name>John</Name></doc>
}
MustToXmlString
-
Description:
MustToXmlStringreturns content inXMLformat as astringtype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToXmlString(rootTag ...string) string
- Example:
func ExampleJson_MustToXmlString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlStr := j.MustToXmlString()
fmt.Println(string(xmlStr))
// Output:
// <doc><Age>18</Age><Name>John</Name></doc>
}
MustToXmlIndent
-
Description:
MustToXmlStringIndentreturns indented content inXMLformat as a[]bytetype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToXmlIndent(rootTag ...string) []byte
- Example:
func ExampleJson_MustToXmlIndent() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlBytes := j.MustToXmlIndent()
fmt.Println(string(xmlBytes))
// Output:
//<doc>
// <Age>18</Age>
// <Name>John</Name>
//</doc>
}
MustToXmlIndentString
-
Description:
MustToXmlStringIndentStringreturns indented content inXMLformat as astringtype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToXmlIndentString(rootTag ...string) string
- Example:
func ExampleJson_MustToXmlIndentString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
xmlStr := j.MustToXmlIndentString()
fmt.Println(string(xmlStr))
// Output:
//<doc>
// <Age>18</Age>
// <Name>John</Name>
//</doc>
}
ToYaml
-
Description:
ToYamlreturns content inYAMLformat as a[]bytetype. -
Format:
func (j *Json) ToYaml() ([]byte, error)
- Example:
func ExampleJson_ToYaml() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
YamlBytes, _ := j.ToYaml()
fmt.Println(string(YamlBytes))
// Output:
//Age: 18
//Name: John
}
ToYamlIndent
-
Description:
ToYamlIndentreturns indented content inYAMLformat as a[]bytetype. -
Format:
func (j *Json) ToYamlIndent(indent string) ([]byte, error)
- Example:
func ExampleJson_ToYamlIndent() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
YamlBytes, _ := j.ToYamlIndent("")
fmt.Println(string(YamlBytes))
// Output:
//Age: 18
//Name: John
}
ToYamlString
-
Description:
ToYamlStringreturns content inYAMLformat as astringtype. -
Format:
func (j *Json) ToYamlString() (string, error)
- Example:
func ExampleJson_ToYamlString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
YamlStr, _ := j.ToYamlString()
fmt.Println(string(YamlStr))
// Output:
//Age: 18
//Name: John
}
MustToYaml
-
Description:
MustToYamlreturns content inYAMLformat as a[]bytetype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToYaml() []byte
- Example:
func ExampleJson_MustToYaml() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
YamlBytes := j.MustToYaml()
fmt.Println(string(YamlBytes))
// Output:
//Age: 18
//Name: John
}
MustToYamlString
-
Description:
MustToYamlStringreturns content inYAMLformat as astringtype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToYamlString() string
- Example:
func ExampleJson_MustToYamlString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
YamlStr := j.MustToYamlString()
fmt.Println(string(YamlStr))
// Output:
//Age: 18
//Name: John
}
ToToml
-
Description:
ToTomlreturns content inTOMLformat as a[]bytetype. -
Format:
func (j *Json) ToToml() ([]byte, error)
- Example:
func ExampleJson_ToToml() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
TomlBytes, _ := j.ToToml()
fmt.Println(string(TomlBytes))
// Output:
//Age = 18
//Name = "John"
}
ToTomlString
-
Description:
ToTomlStringreturns content inTOMLformat as astringtype. -
Format:
func (j *Json) ToTomlString() (string, error)
- Example:
func ExampleJson_ToTomlString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
TomlStr, _ := j.ToTomlString()
fmt.Println(string(TomlStr))
// Output:
//Age = 18
//Name = "John"
}
MustToToml
-
Description:
MustToTomlreturns content inTOMLformat as a[]bytetype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToToml() []byte
- Example:
func ExampleJson_MustToToml() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
TomlBytes := j.MustToToml()
fmt.Println(string(TomlBytes))
// Output:
//Age = 18
//Name = "John"
}
MustToTomlString
-
Description:
MustToTomlStringreturns content inTOMLformat as astringtype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToTomlString() string
- Example:
func ExampleJson_MustToTomlString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
TomlStr := j.MustToTomlString()
fmt.Println(string(TomlStr))
// Output:
//Age = 18
//Name = "John"
}
ToIni
-
Description:
ToInireturns content inINIformat as a[]bytetype. -
Format:
func (j *Json) ToIni() ([]byte, error)
- Example:
func ExampleJson_ToIni() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
IniBytes, _ := j.ToIni()
fmt.Println(string(IniBytes))
// May Output:
//Name=John
//Age=18
}
ToIniString
-
Description:
ToIniStringreturns content inINIformat as astringtype. -
Format:
func (j *Json) ToIniString() (string, error)
- Example:
func ExampleJson_ToIniString() {
type BaseInfo struct {
Name string
}
info := BaseInfo{
Name: "John",
}
j := gjson.New(info)
IniStr, _ := j.ToIniString()
fmt.Println(string(IniStr))
// Output:
//Name=John
}
MustToIni
-
Description:
MustToInireturns content inINIformat as a[]bytetype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToIni() []byte
- Example:
func ExampleJson_MustToIni() {
type BaseInfo struct {
Name string
}
info := BaseInfo{
Name: "John",
}
j := gjson.New(info)
IniBytes := j.MustToIni()
fmt.Println(string(IniBytes))
// Output:
//Name=John
}
MustToIniString
-
Description:
MustToIniStringreturns content inINIformat as astringtype. If any error occurs, it willpanic. -
Format:
func (j *Json) MustToIniString() string
- Example:
func ExampleJson_MustToIniString() {
type BaseInfo struct {
Name string
}
info := BaseInfo{
Name: "John",
}
j := gjson.New(info)
IniStr := j.MustToIniString()
fmt.Println(string(IniStr))
// Output:
//Name=John
}
MarshalJSON
-
Description:
MarshalJSONimplements thejson.MarshalinterfaceMarshalJSON. -
Format:
func (j Json) MarshalJSON() ([]byte, error)
- Example:
func ExampleJson_MarshalJSON() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
jsonBytes, _ := j.MarshalJSON()
fmt.Println(string(jsonBytes))
// Output:
// {"Age":18,"Name":"John"}
}
UnmarshalJSON
-
Description:
UnmarshalJSONimplements thejson.UnmarshalinterfaceUnmarshalJSON. -
Format:
func (j *Json) UnmarshalJSON(b []byte) error
- Example:
func ExampleJson_UnmarshalJSON() {
jsonStr := `{"Age":18,"Name":"John"}`
j := gjson.New("")
j.UnmarshalJSON([]byte(jsonStr))
fmt.Println(j.Map())
// Output:
// map[Age:18 Name:John]
}
UnmarshalValue
-
Description:
UnmarshalValueis an interface implementation for setting any type of value toJson. -
Format:
func (j *Json) UnmarshalValue(value interface{}) error
- Example:
func ExampleJson_UnmarshalValue_Yaml() {
yamlContent :=
`base:
name: john
score: 100`
j := gjson.New("")
j.UnmarshalValue([]byte(yamlContent))
fmt.Println(j.Var().String())
// Output:
// {"base":{"name":"john","score":100}}
}
func ExampleJson_UnmarshalValue_Xml() {
xmlStr := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>`
j := gjson.New("")
j.UnmarshalValue([]byte(xmlStr))
fmt.Println(j.Var().String())
// Output:
// {"doc":{"name":"john","score":"100"}}
}
MapStrAny
-
Description:
MapStrAnyimplements the interface methodMapStrAny(). -
Format:
func (j *Json) MapStrAny() map[string]interface{}
- Example:
func ExampleJson_MapStrAny() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
fmt.Println(j.MapStrAny())
// Output:
// map[Age:18 Name:John]
}
Interfaces
-
Description:
Interfacesimplements the interface methodInterfaces(). -
Format:
func (j *Json) Interfaces() []interface{}
- Example:
func ExampleJson_Interfaces() {
type BaseInfo struct {
Name string
Age int
}
infoList := []BaseInfo{
BaseInfo{
Name: "John",
Age: 18,
},
BaseInfo{
Name: "Tom",
Age: 20,
},
}
j := gjson.New(infoList)
fmt.Println(j.Interfaces())
// Output:
// [{John 18} {Tom 20}]
}
Interface
-
Description:
Interfacereturns the value of theJsonobject. -
Format:
func (j *Json) Interface() interface{}
- Example:
func ExampleJson_Interface() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
fmt.Println(j.Interface())
var nilJ *gjson.Json = nil
fmt.Println(nilJ.Interface())
// Output:
// map[Age:18 Name:John]
// <nil>
}
Var
-
Description:
Varreturns the value of theJsonobject as type*gvar.Var. -
Format:
func (j *Json) Var() *gvar.Var
- Example:
func ExampleJson_Var() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
fmt.Println(j.Var().String())
fmt.Println(j.Var().Map())
// Output:
// {"Age":18,"Name":"John"}
// map[Age:18 Name:John]
}
IsNil
-
Description:
IsNilchecks whether the Json object's value isnil. -
Format:
func (j *Json) IsNil() bool
- Example:
func ExampleJson_IsNil() {
data1 := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
data2 := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]`)
j1, _ := gjson.LoadContent(data1)
fmt.Println(j1.IsNil())
j2, _ := gjson.LoadContent(data2)
fmt.Println(j2.IsNil())
// Output:
// false
// true
}
Get
-
Description:
Getretrieves and returns the value according to the specifiedpattern. If thepatternis".", it will return all values of the currentJsonobject. If nopatternis found, it returnsnil`. -
Format:
func (j *Json) Get(pattern string, def ...interface{}) *gvar.Var
- Example:
func ExampleJson_Get() {
data :=
`{
"users" : {
"count" : 1,
"array" : ["John", "Ming"]
}
}`
j, _ := gjson.LoadContent(data)
fmt.Println(j.Get("."))
fmt.Println(j.Get("users"))
fmt.Println(j.Get("users.count"))
fmt.Println(j.Get("users.array"))
var nilJ *gjson.Json = nil
fmt.Println(nilJ.Get("."))
// Output:
// {"users":{"array":["John","Ming"],"count":1}}
// {"array":["John","Ming"],"count":1}
// 1
// ["John","Ming"]
}
GetJson
-
Description:
GetJsonretrieves the value specified bypatternand converts it into a non-concurrent-safeJsonobject. -
Format:
func (j *Json) GetJson(pattern string, def ...interface{}) *Json
- Example:
func ExampleJson_GetJson() {
data :=
`{
"users" : {
"count" : 1,
"array" : ["John", "Ming"]
}
}`
j, _ := gjson.LoadContent(data)
fmt.Println(j.GetJson("users.array").Array())
// Output:
// [John Ming]
}
GetJsons
-
Description:
GetJsonsretrieves the value specified bypatternand converts it into a slice of non-concurrent-safeJsonobjects. -
Format:
func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json
- Example:
func ExampleJson_GetJsons() {
data :=
`{
"users" : {
"count" : 3,
"array" : [{"Age":18,"Name":"John"}, {"Age":20,"Name":"Tom"}]
}
}`
j, _ := gjson.LoadContent(data)
jsons := j.GetJsons("users.array")
for _, json := range jsons {
fmt.Println(json.Interface())
}
// Output:
// map[Age:18 Name:John]
// map[Age:20 Name:Tom]
}
GetJsonMap
-
Description:
GetJsonMapretrieves the value specified bypatternand converts it into a map of non-concurrent-safeJsonobjects. -
Format:
func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json
- Example:
func ExampleJson_GetJsonMap() {
data :=
`{
"users" : {
"count" : 1,
"array" : {
"info" : {"Age":18,"Name":"John"},
"addr" : {"City":"Chengdu","Company":"Tencent"}
}
}
}`
j, _ := gjson.LoadContent(data)
jsonMap := j.GetJsonMap("users.array")
for _, json := range jsonMap {
fmt.Println(json.Interface())
}
// May Output:
// map[City:Chengdu Company:Tencent]
// map[Age:18 Name:John]
}
Set
-
Description:
Setsets the value of the specifiedpattern. It supports data level access by default using the'.'character. -
Format:
func (j *Json) Set(pattern string, value interface{}) error
- Example:
func ExampleJson_Set() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
j.Set("Addr", "ChengDu")
j.Set("Friends.0", "Tom")
fmt.Println(j.Var().String())
// Output:
// {"Addr":"ChengDu","Age":18,"Friends":["Tom"],"Name":"John"}
}
MustSet
-
Description:
MustSetperforms theSetoperation, but if any error occurs, it willpanic. -
Format:
func (j *Json) MustSet(pattern string, value interface{})
- Example:
func ExampleJson_MustSet() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
j.MustSet("Addr", "ChengDu")
fmt.Println(j.Var().String())
// Output:
// {"Addr":"ChengDu","Age":18,"Name":"John"}
}
Remove
-
Description:
Removedeletes the value of the specifiedpattern. It supports data level access by default using the'.'character. -
Format:
func (j *Json) Remove(pattern string) error
- Example:
func ExampleJson_Remove() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
j.Remove("Age")
fmt.Println(j.Var().String())
// Output:
// {"Name":"John"}
}
MustRemove
-
Description:
MustRemoveperformsRemove, but if any error occurs, it willpanic. -
Format:
func (j *Json) MustRemove(pattern string)
- Example:
func ExampleJson_MustRemove() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
j.MustRemove("Age")
fmt.Println(j.Var().String())
// Output:
// {"Name":"John"}
}
Contains
-
Description:
Containschecks if the value of the specifiedpatternexists. -
Format:
func (j *Json) Contains(pattern string) bool
- Example:
func ExampleJson_Contains() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
fmt.Println(j.Contains("Age"))
fmt.Println(j.Contains("Addr"))
// Output:
// true
// false
}
Len
-
Description:
Lenreturns the length/size of a value according to the specifiedpattern. The type of thepatternvalue should be asliceor amap. If the target value is not found or the type is invalid, it returns-1. -
Format:
func (j *Json) Len(pattern string) int
- Example:
func ExampleJson_Len() {
data :=
`{
"users" : {
"count" : 1,
"nameArray" : ["Join", "Tom"],
"infoMap" : {
"name" : "Join",
"age" : 18,
"addr" : "ChengDu"
}
}
}`
j, _ := gjson.LoadContent(data)
fmt.Println(j.Len("users.nameArray"))
fmt.Println(j.Len("users.infoMap"))
// Output:
// 2
// 3
}
Append
-
Description:
Appendappends a value to theJsonobject using the specifiedpattern. The type of thepatternvalue should be aslice. -
Format:
func (j *Json) Append(pattern string, value interface{}) error
- Example:
func ExampleJson_Append() {
data :=
`{
"users" : {
"count" : 1,
"array" : ["John", "Ming"]
}
}`
j, _ := gjson.LoadContent(data)
j.Append("users.array", "Lily")
fmt.Println(j.Get("users.array").Array())
// Output:
// [John Ming Lily]
}
MustAppend
-
Description:
MustAppendperformsAppend, but if any error occurs, it willpanic. -
Format:
func (j *Json) MustAppend(pattern string, value interface{})
- Example:
func ExampleJson_MustAppend() {
data :=
`{
"users" : {
"count" : 1,
"array" : ["John", "Ming"]
}
}`
j, _ := gjson.LoadContent(data)
j.MustAppend("users.array", "Lily")
fmt.Println(j.Get("users.array").Array())
// Output:
// [John Ming Lily]
}
Map
-
Description:
Mapconverts the currentJsonobject to amap[string]interface{}. It returnsnilif conversion fails. -
Format:
func (j *Json) Map() map[string]interface{}
- Example:
func ExampleJson_Map() {
data :=
`{
"users" : {
"count" : 1,
"info" : {
"name" : "John",
"age" : 18,
"addr" : "ChengDu"
}
}
}`
j, _ := gjson.LoadContent(data)
fmt.Println(j.Get("users.info").Map())
// Output:
// map[addr:ChengDu age:18 name:John]
}
Array
-
Description:
Arrayconverts the currentJsonobject to a[]interface{}. It returnsnilif conversion fails. -
Format:
func (j *Json) Array() []interface{}
- Example:
func ExampleJson_Array() {
data :=
`{
"users" : {
"count" : 1,
"array" : ["John", "Ming"]
}
}`
j, _ := gjson.LoadContent(data)
fmt.Println(j.Get("users.array"))
// Output:
// ["John","Ming"]
}
Scan
-
Description:
Scanautomatically calls theStructorStructsfunction to perform conversion based on the type of thepointerparameter. -
Format:
func (j *Json) Scan(pointer interface{}, mapping ...map[string]string) error
- Example:
func ExampleJson_Scan() {
data := `{"name":"john","age":"18"}`
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{}
j, _ := gjson.LoadContent(data)
j.Scan(&info)
fmt.Println(info)
// May Output:
// {john 18}
}
Dump
-
Description:
Dumpprints theJsonobject in a more readable way. -
Format:
func (j *Json) Dump()
- Example:
func ExampleJson_Dump() {
data := `{"name":"john","age":"18"}`
j, _ := gjson.LoadContent(data)
j.Dump()
// May Output:
//{
// "name": "john",
// "age": "18",
//}
}