Skip to main content
Version: 2.8.x(Latest)
tip

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: New can create a Json object with any type of value data. However, due to data access reasons, data should be a map or slice, otherwise it is meaningless.

  • Note: The safe parameter determines whether the Json object is concurrent-safe, defaulting to false.

  • 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: NewWithTag can create a Json object with any type of value data. However, due to data access reasons, data should be a map or slice, otherwise it is meaningless.

  • Note: The tgts parameter specifies the priority of tag names when converting structs to maps, with multiple tags separated by ','.

  • The safe parameter determines whether the Json object is concurrent-safe, defaulting to false.

  • 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: NewWithOptions can create a Json object with any type of value data. However, due to data access reasons, data should be a map or slice, 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: Load loads content from the specified file path and creates a Json object 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: LoadJson creates a Json object from the given content in JSON format.

  • 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: LoadXml creates a Json object from the given content in XML format.

  • 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: LoadIni creates a Json object from the given content in INI format.

  • 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: LoadYaml creates a Json object from the given content in YAML format.

  • 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: LoadToml creates a Json object from the given content in TOML format.

  • 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: LoadContent creates a Json object based on the given content. It automatically checks the data type of content, supporting content types such as JSON, 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: LoadContentType creates a Json object based on the given content and type. Supported content types are Json, 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: IsValidDataType checks if the given dataType is 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: Valid checks if data is a valid JSON data type. The data parameter specifies the JSON formatted data, which can be of type bytes or string.

  • 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: Marshal is an alias for Encode.

  • 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: MarshalIndent is an alias for json.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: Unmarshal is an alias for DecodeTo.

  • 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: Encode serializes any type value into a byte array with content in JSON format.

  • 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: MustEncode performs the Encode operation but will panic if 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: EncodeString serializes any type value into a string with content in JSON format.

  • 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: MustEncodeString serializes any type value into a string with content in JSON format but will panic if 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: Decode decodes data in JSON format to interface{}. The data parameter can be []byte or string.

  • 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: DecodeTo decodes data in JSON format to the specified interface type variable v. The data parameter can be []byte or string. The v parameter 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: DecodeToJson encodes data in JSON format into a json object. The data parameter can be []byte or string.

  • 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: SetSplitChar sets 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: SetViolenceCheck enables/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: ToJson returns the JSON content as a []byte type.

  • 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: ToJsonString returns the JSON content as a string type.

  • 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: ToJsonIndent returns the indented JSON content as a []byte type.

  • 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: ToJsonIndentString returns the indented JSON content as a string type.

  • 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: MustToJson returns the JSON content as a []byte type, and if any error occurs, it will panic.

  • 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: MustToJsonString returns the JSON content as a string type, and if any error occurs, it will panic.

  • 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: MustToJsonStringIndent returns the indented JSON content as a []byte type, and if any error occurs, it will panic.

  • 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: MustToJsonStringIndent returns the indented JSON content as a string type, and if any error occurs, it will panic.

  • 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: ToXml returns content in XML format as a []byte type.

  • 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: ToXmlString returns content in XML format as a string type.

  • 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: ToXmlIndent returns indented content in XML format as a []byte type.

  • 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: ToXmlIndentString returns indented content in XML format as a string type.

  • 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: MustToXml returns content in XML format as a []byte type. If any error occurs, it will panic.

  • 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: MustToXmlString returns content in XML format as a string type. If any error occurs, it will panic.

  • 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: MustToXmlStringIndent returns indented content in XML format as a []byte type. If any error occurs, it will panic.

  • 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: MustToXmlStringIndentString returns indented content in XML format as a string type. If any error occurs, it will panic.

  • 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: ToYaml returns content in YAML format as a []byte type.

  • 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: ToYamlIndent returns indented content in YAML format as a []byte type.

  • 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: ToYamlString returns content in YAML format as a string type.

  • 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: MustToYaml returns content in YAML format as a []byte type. If any error occurs, it will panic.

  • 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: MustToYamlString returns content in YAML format as a string type. If any error occurs, it will panic.

  • 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: ToToml returns content in TOML format as a []byte type.

  • 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: ToTomlString returns content in TOML format as a string type.

  • 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: MustToToml returns content in TOML format as a []byte type. If any error occurs, it will panic.

  • 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: MustToTomlString returns content in TOML format as a string type. If any error occurs, it will panic.

  • 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: ToIni returns content in INI format as a []byte type.

  • 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: ToIniString returns content in INI format as a string type.

  • 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: MustToIni returns content in INI format as a []byte type. If any error occurs, it will panic.

  • 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: MustToIniString returns content in INI format as a string type. If any error occurs, it will panic.

  • 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: MarshalJSON implements the json.Marshal interface MarshalJSON.

  • 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: UnmarshalJSON implements the json.Unmarshal interface UnmarshalJSON.

  • 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: UnmarshalValue is an interface implementation for setting any type of value to Json.

  • 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: MapStrAny implements the interface method MapStrAny().

  • 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: Interfaces implements the interface method Interfaces().

  • 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: Interface returns the value of the Json object.

  • 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: Var returns the value of the Json object 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: IsNil checks whether the Json object's value is nil.

  • 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: Get retrieves and returns the value according to the specified pattern. If the pattern is ".", it will return all values of the current Jsonobject. 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: GetJson retrieves the value specified by pattern and converts it into a non-concurrent-safe Json object.

  • 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: GetJsons retrieves the value specified by pattern and converts it into a slice of non-concurrent-safe Json objects.

  • 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: GetJsonMap retrieves the value specified by pattern and converts it into a map of non-concurrent-safe Json objects.

  • 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: Set sets the value of the specified pattern. 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: MustSet performs the Set operation, but if any error occurs, it will panic.

  • 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: Remove deletes the value of the specified pattern. 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: MustRemove performs Remove, but if any error occurs, it will panic.

  • 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: Contains checks if the value of the specified pattern exists.

  • 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: Len returns the length/size of a value according to the specified pattern. The type of the pattern value should be a slice or a map. 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: Append appends a value to the Json object using the specified pattern. The type of the pattern value should be a slice.

  • 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: MustAppend performs Append, but if any error occurs, it will panic.

  • 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: Map converts the current Json object to a map[string]interface{}. It returns nil if 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: Array converts the current Json object to a []interface{}. It returns nil if 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: Scan automatically calls the Struct or Structs function to perform conversion based on the type of the pointer parameter.

  • 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: Dump prints the Json object 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",
//}
}