New
NewWithTag
NewWithOptions
Load
LoadJson
LoadXml
- LoadIni
LoadYaml
LoadToml
LoadContent
- LoadContentType
IsValidDataType
Valid
- Marshal
MarshalIndent
- Unmarshal
- Encode
MustEncode
EncodeString
MustEncodeString
Decode
- DecodeTo
DecodeToJson
SetSplitChar
SetViolenceCheck
ToJson
ToJsonString
- ToJsonIndent
ToJsonIndentString
- MustToJson
MustToJsonString
- MustToJsonIndent
MustToJsonIndentString
- ToXml
ToXmlString
- ToXmlIndent
ToXmlIndentString
- MustToXml
MustToXmlString
- MustToXmlIndent
MustToXmlIndentString
- ToYaml
- ToYamlIndent
ToYamlString
MustToYaml
- MustToYamlString
ToToml
- ToTomlString
MustToToml
- MustToTomlString
ToIni
- ToIniString
MustToIni
- MustToIniString
- MarshalJSON
- UnmarshalJSON
UnmarshalValue
MapStrAny
- Interfaces
Interface
Var
- IsNil
Get
GetJson
- GetJsons
GetJsonMap
Set
MustSet
Remove
- MustRemove
Contains
- Len
Append
- MustAppend
- Map
- Array
Scan
- Dump
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 aJson
object with any type of valuedata
. However, due to data access reasons,data
should be amap
orslice
, otherwise it is meaningless.Note: The
safe
parameter determines whether theJson
object 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:
NewWithTag
can create aJson
object with any type of valuedata
. However, due to data access reasons,data
should be amap
orslice
, 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 theJson
object 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:
NewWithOptions
can create aJson
object with any type of valuedata
. However, due to data access reasons,data
should be amap
orslice
, 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 filepath
and creates aJson
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 aJson
object from the given content inJSON
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 aJson
object from the given content inXML
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 aJson
object from the given content inINI
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 aJson
object from the given content inYAML
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 aJson
object from the given content inTOML
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 aJson
object 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:
LoadContentType
creates aJson
object 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:
IsValidDataType
checks if the givendataType
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 ifdata
is a validJSON
data type. Thedata
parameter specifies theJSON
formatted data, which can be of typebytes
orstring
.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 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:
MarshalIndent
is 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:
Unmarshal
is 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:
Encode
serializes any typevalue
into abyte
array with content inJSON
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 theEncode
operation but willpanic
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 typevalue
into astring
with content inJSON
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 typevalue
into astring
with content inJSON
format but willpanic
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
decodesdata
inJSON
format tointerface{}
. Thedata
parameter can be[]byte
orstring
.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
decodesdata
inJSON
format to the specifiedinterface
type variablev
. Thedata
parameter can be[]byte
orstring
. Thev
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
encodesdata
inJSON
format into ajson
object. Thedata
parameter can be[]byte
orstring
.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 theJSON
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 theJSON
content as astring
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 indentedJSON
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 indentedJSON
content as astring
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 theJSON
content as a[]byte
type, 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:
MustToJsonString
returns theJSON
content as astring
type, 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:
MustToJsonStringIndent
returns the indentedJSON
content as a[]byte
type, 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:
MustToJsonStringIndent
returns the indentedJSON
content as astring
type, 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:
ToXml
returns content inXML
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 inXML
format as astring
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 inXML
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 inXML
format as astring
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 inXML
format as a[]byte
type. 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:
MustToXmlString
returns content inXML
format as astring
type. 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:
MustToXmlStringIndent
returns indented content inXML
format as a[]byte
type. 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:
MustToXmlStringIndentString
returns indented content inXML
format as astring
type. 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:
ToYaml
returns content inYAML
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 inYAML
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 inYAML
format as astring
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 inYAML
format as a[]byte
type. 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:
MustToYamlString
returns content inYAML
format as astring
type. 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:
ToToml
returns content inTOML
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 inTOML
format as astring
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 inTOML
format as a[]byte
type. 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:
MustToTomlString
returns content inTOML
format as astring
type. 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:
ToIni
returns content inINI
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 inINI
format as astring
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 inINI
format as a[]byte
type. 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:
MustToIniString
returns content inINI
format as astring
type. 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:
MarshalJSON
implements thejson.Marshal
interfaceMarshalJSON
.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 thejson.Unmarshal
interfaceUnmarshalJSON
.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 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:
MapStrAny
implements 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:
Interfaces
implements 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:
Interface
returns the value of theJson
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 theJson
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 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:
Get
retrieves and returns the value according to the specifiedpattern
. If thepattern
is".", it will return all values of the current
Jsonobject. If no
patternis found, it returns
nil`.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 bypattern
and converts it into a non-concurrent-safeJson
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 bypattern
and converts it into a slice of non-concurrent-safeJson
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 bypattern
and converts it into a map of non-concurrent-safeJson
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 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:
MustSet
performs theSet
operation, 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:
Remove
deletes 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:
MustRemove
performsRemove
, 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:
Contains
checks if the value of the specifiedpattern
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 specifiedpattern
. The type of thepattern
value should be aslice
or 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:
Append
appends a value to theJson
object using the specifiedpattern
. The type of thepattern
value 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:
MustAppend
performsAppend
, 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:
Map
converts the currentJson
object to amap[string]interface{}
. It returnsnil
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 currentJson
object to a[]interface{}
. It returnsnil
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 theStruct
orStructs
function to perform conversion based on the type of thepointer
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 theJson
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",
//}
}