gjson

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2021 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package gjson provides convenient API for JSON/XML/INI/YAML/TOML data handling.

Example (ConversionGetStruct)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	data :=
		`{
        "users" : {
            "count" : 1,
            "array" : ["John", "Ming"]
        }
    }`
	if j, err := gjson.DecodeToJson(data); err != nil {
		panic(err)
	} else {
		type Users struct {
			Count int
			Array []string
		}
		users := new(Users)
		if err := j.Get("users").Scan(users); err != nil {
			panic(err)
		}
		fmt.Printf(`%+v`, users)
	}

}
Output:

&{Count:1 Array:[John Ming]}
Example (ConversionNormalFormats)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	data :=
		`{
        "users" : {
            "count" : 1,
            "array" : ["John", "Ming"]
        }
    }`

	if j, err := gjson.DecodeToJson(data); err != nil {
		panic(err)
	} else {
		fmt.Println("JSON:")
		fmt.Println(j.MustToJsonString())
		fmt.Println("======================")

		fmt.Println("XML:")
		fmt.Println(j.MustToXmlString())
		fmt.Println("======================")

		fmt.Println("YAML:")
		fmt.Println(j.MustToYamlString())
		fmt.Println("======================")

		fmt.Println("TOML:")
		fmt.Println(j.MustToTomlString())
	}

}
Output:

JSON:
{"users":{"array":["John","Ming"],"count":1}}
======================
XML:
<users><array>John</array><array>Ming</array><count>1</count></users>
======================
YAML:
users:
    array:
        - John
        - Ming
    count: 1

======================
TOML:
[users]
  array = ["John", "Ming"]
  count = 1.0
Example (ConversionToStruct)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	data :=
		`
	{
        "count" : 1,
        "array" : ["John", "Ming"]
    }`
	if j, err := gjson.DecodeToJson(data); err != nil {
		panic(err)
	} else {
		type Users struct {
			Count int
			Array []string
		}
		users := new(Users)
		if err := j.Var().Scan(users); err != nil {
			panic(err)
		}
		fmt.Printf(`%+v`, users)
	}

}
Output:

&{Count:1 Array:[John Ming]}
Example (DataSetCreate1)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	j := gjson.New(nil)
	j.Set("name", "John")
	j.Set("score", 99.5)
	fmt.Printf(
		"Name: %s, Score: %v\n",
		j.Get("name").String(),
		j.Get("score").Float32(),
	)
	fmt.Println(j.MustToJsonString())

}
Output:

Name: John, Score: 99.5
{"name":"John","score":99.5}
Example (DataSetCreate2)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	j := gjson.New(nil)
	for i := 0; i < 5; i++ {
		j.Set(fmt.Sprintf(`%d.id`, i), i)
		j.Set(fmt.Sprintf(`%d.name`, i), fmt.Sprintf(`student-%d`, i))
	}
	fmt.Println(j.MustToJsonString())

}
Output:

[{"id":0,"name":"student-0"},{"id":1,"name":"student-1"},{"id":2,"name":"student-2"},{"id":3,"name":"student-3"},{"id":4,"name":"student-4"}]
Example (DataSetRuntimeEdit)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	data :=
		`{
        "users" : {
            "count" : 2,
            "list"  : [
                {"name" : "Ming", "score" : 60},
                {"name" : "John", "score" : 59}
            ]
        }
    }`
	if j, err := gjson.DecodeToJson(data); err != nil {
		panic(err)
	} else {
		j.Set("users.list.1.score", 100)
		fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
		fmt.Println(j.MustToJsonString())
	}
}
Output:

John Score: 100
{"users":{"count":2,"list":[{"name":"Ming","score":60},{"name":"John","score":100}]}}
Example (LoadContent)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	jsonContent := `{"name":"john", "score":"100"}`
	j, _ := gjson.LoadContent(jsonContent)
	fmt.Println(j.Get("name"))
	fmt.Println(j.Get("score"))
}
Output:

john
100
Example (LoadJson)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/debug/gdebug"
	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	jsonFilePath := gdebug.TestDataPath("json", "data1.json")
	j, _ := gjson.Load(jsonFilePath)
	fmt.Println(j.Get("name"))
	fmt.Println(j.Get("score"))
}
Output:

Example (LoadXml)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/debug/gdebug"
	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	jsonFilePath := gdebug.TestDataPath("xml", "data1.xml")
	j, _ := gjson.Load(jsonFilePath)
	fmt.Println(j.Get("doc.name"))
	fmt.Println(j.Get("doc.score"))
}
Output:

Example (MapSliceChange)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	jsonContent := `{"map":{"key":"value"}, "slice":[59,90]}`
	j, _ := gjson.LoadJson(jsonContent)
	m := j.Get("map").Map()
	fmt.Println(m)

	// Change the key-value pair.
	m["key"] = "john"

	// It changes the underlying key-value pair.
	fmt.Println(j.Get("map").Map())

	s := j.Get("slice").Array()
	fmt.Println(s)

	// Change the value of specified index.
	s[0] = 100

	// It changes the underlying slice.
	fmt.Println(j.Get("slice").Array())

}
Output:

map[key:value]
map[key:john]
[59 90]
[100 90]
Example (NewFromJson)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	jsonContent := `{"name":"john", "score":"100"}`
	j := gjson.New(jsonContent)
	fmt.Println(j.Get("name"))
	fmt.Println(j.Get("score"))
}
Output:

john
100
Example (NewFromStruct)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	type Me struct {
		Name  string `json:"name"`
		Score int    `json:"score"`
	}
	me := Me{
		Name:  "john",
		Score: 100,
	}
	j := gjson.New(me)
	fmt.Println(j.Get("name"))
	fmt.Println(j.Get("score"))
}
Output:

john
100
Example (NewFromStructWithTag)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	type Me struct {
		Name  string `tag:"name"`
		Score int    `tag:"score"`
		Title string
	}
	me := Me{
		Name:  "john",
		Score: 100,
		Title: "engineer",
	}
	// The parameter `tags` specifies custom priority tags for struct conversion to map,
	// multiple tags joined with char ','.
	j := gjson.NewWithTag(me, "tag")
	fmt.Println(j.Get("name"))
	fmt.Println(j.Get("score"))
	fmt.Println(j.Get("Title"))
}
Output:

john
100
engineer
Example (NewFromXml)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	jsonContent := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>`
	j := gjson.New(jsonContent)
	// Note that there's root node in the XML content.
	fmt.Println(j.Get("doc.name"))
	fmt.Println(j.Get("doc.score"))
}
Output:

john
100
Example (PatternCustomSplitChar)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	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
Example (PatternGet)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	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 {
		fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
	}
}
Output:

John Score: 99.5
Example (PatternViolenceCheck)
package main

import (
	"fmt"

	"easyscdp.com/gogf/gf/encoding/gjson"
)

func main() {
	data :=
		`{
        "users" : {
            "count" : 100
        },
        "users.count" : 101
    }`
	if j, err := gjson.DecodeToJson(data); err != nil {
		panic(err)
	} else {
		j.SetViolenceCheck(true)
		fmt.Println("Users Count:", j.Get("users.count").Int())
	}
}
Output:

Users Count: 101

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(data interface{}) (interface{}, error)

Decode decodes json format `data` to golang variable. The parameter `data` can be either bytes or string type.

func DecodeTo

func DecodeTo(data interface{}, v interface{}) error

DecodeTo decodes json format `data` to specified golang variable `v`. The parameter `data` can be either bytes or string type. The parameter `v` should be a pointer type.

func Encode

func Encode(value interface{}) ([]byte, error)

Encode encodes any golang variable `value` to JSON bytes.

func IsValidDataType

func IsValidDataType(dataType string) bool

IsValidDataType checks and returns whether given `dataType` a valid data type for loading.

func Valid

func Valid(data interface{}) bool

Valid checks whether `data` is a valid JSON data type. The parameter `data` specifies the json format data, which can be either bytes or string type.

Types

type Json

type Json struct {
	// contains filtered or unexported fields
}

Json is the customized JSON struct.

func DecodeToJson

func DecodeToJson(data interface{}, safe ...bool) (*Json, error)

DecodeToJson codes json format `data` to a Json object. The parameter `data` can be either bytes or string type.

func Load

func Load(path string, safe ...bool) (*Json, error)

Load loads content from specified file `path`, and creates a Json object from its content.

func LoadContent

func LoadContent(data interface{}, safe ...bool) (*Json, error)

LoadContent creates a Json object from given content, it checks the data type of `content` automatically, supporting data content type as follows: JSON, XML, INI, YAML and TOML.

func LoadContentType

func LoadContentType(dataType string, data interface{}, safe ...bool) (*Json, error)

LoadContentType creates a Json object from given type and content, supporting data content type as follows: JSON, XML, INI, YAML and TOML.

func LoadIni

func LoadIni(data interface{}, safe ...bool) (*Json, error)

LoadIni creates a Json object from given INI format content.

func LoadJson

func LoadJson(data interface{}, safe ...bool) (*Json, error)

LoadJson creates a Json object from given JSON format content.

func LoadToml

func LoadToml(data interface{}, safe ...bool) (*Json, error)

LoadToml creates a Json object from given TOML format content.

func LoadXml

func LoadXml(data interface{}, safe ...bool) (*Json, error)

LoadXml creates a Json object from given XML format content.

func LoadYaml

func LoadYaml(data interface{}, safe ...bool) (*Json, error)

LoadYaml creates a Json object from given YAML format content.

func New

func New(data interface{}, safe ...bool) *Json

New creates a Json object with any variable type of `data`, but `data` should be a map or slice for data access reason, or it will make no sense.

The parameter `safe` specifies whether using this Json object in concurrent-safe context, which is false in default.

func NewWithOptions

func NewWithOptions(data interface{}, options Options) *Json

NewWithOptions creates a Json object with any variable type of `data`, but `data` should be a map or slice for data access reason, or it will make no sense.

func NewWithTag

func NewWithTag(data interface{}, tags string, safe ...bool) *Json

NewWithTag creates a Json object with any variable type of `data`, but `data` should be a map or slice for data access reason, or it will make no sense.

The parameter `tags` specifies priority tags for struct conversion to map, multiple tags joined with char ','.

The parameter `safe` specifies whether using this Json object in concurrent-safe context, which is false in default.

func (*Json) Append

func (j *Json) Append(pattern string, value interface{}) error

Append appends value to the value by specified `pattern`. The target value by `pattern` should be type of slice.

func (*Json) Array

func (j *Json) Array() []interface{}

Array converts current Json object to []interface{}. It returns nil if fails.

func (*Json) Contains

func (j *Json) Contains(pattern string) bool

Contains checks whether the value by specified `pattern` exist.

func (*Json) Dump

func (j *Json) Dump()

Dump prints current Json object with more manually readable.

func (*Json) Get

func (j *Json) Get(pattern string, def ...interface{}) *gvar.Var

Get retrieves and returns value by specified `pattern`. It returns all values of current Json object if `pattern` is given empty or string ".". It returns nil if no value found by `pattern`.

We can also access slice item by its index number in `pattern` like: "list.10", "array.0.name", "array.0.1.id".

It returns a default value specified by `def` if value for `pattern` is not found.

func (*Json) GetJson

func (j *Json) GetJson(pattern string, def ...interface{}) *Json

GetJson gets the value by specified `pattern`, and converts it to a un-concurrent-safe Json object.

func (*Json) GetJsonMap

func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json

GetJsonMap gets the value by specified `pattern`, and converts it to a map of un-concurrent-safe Json object.

func (*Json) GetJsons

func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json

GetJsons gets the value by specified `pattern`, and converts it to a slice of un-concurrent-safe Json object.

func (*Json) Interface

func (j *Json) Interface() interface{}

Interface returns the json value.

func (*Json) IsNil

func (j *Json) IsNil() bool

IsNil checks whether the value pointed by `j` is nil.

func (*Json) Len

func (j *Json) Len(pattern string) int

Len returns the length/size of the value by specified `pattern`. The target value by `pattern` should be type of slice or map. It returns -1 if the target value is not found, or its type is invalid.

func (*Json) Map

func (j *Json) Map() map[string]interface{}

Map converts current Json object to map[string]interface{}. It returns nil if fails.

func (*Json) MarshalJSON

func (j *Json) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

func (*Json) MustToIni

func (j *Json) MustToIni() []byte

func (*Json) MustToIniString

func (j *Json) MustToIniString() string

MustToIniString .

func (*Json) MustToJson

func (j *Json) MustToJson() []byte

func (*Json) MustToJsonIndent

func (j *Json) MustToJsonIndent() []byte

func (*Json) MustToJsonIndentString

func (j *Json) MustToJsonIndentString() string

func (*Json) MustToJsonString

func (j *Json) MustToJsonString() string

func (*Json) MustToToml

func (j *Json) MustToToml() []byte

func (*Json) MustToTomlString

func (j *Json) MustToTomlString() string

func (*Json) MustToXml

func (j *Json) MustToXml(rootTag ...string) []byte

func (*Json) MustToXmlIndent

func (j *Json) MustToXmlIndent(rootTag ...string) []byte

func (*Json) MustToXmlIndentString

func (j *Json) MustToXmlIndentString(rootTag ...string) string

func (*Json) MustToXmlString

func (j *Json) MustToXmlString(rootTag ...string) string

func (*Json) MustToYaml

func (j *Json) MustToYaml() []byte

func (*Json) MustToYamlString

func (j *Json) MustToYamlString() string

func (*Json) Remove

func (j *Json) Remove(pattern string) error

Remove deletes value with specified `pattern`. It supports hierarchical data access by char separator, which is '.' in default.

func (*Json) Scan

func (j *Json) Scan(pointer interface{}, mapping ...map[string]string) error

Scan automatically calls Struct or Structs function according to the type of parameter `pointer` to implement the converting.

func (*Json) Set

func (j *Json) Set(pattern string, value interface{}) error

Set sets value with specified `pattern`. It supports hierarchical data access by char separator, which is '.' in default.

func (*Json) SetSplitChar

func (j *Json) SetSplitChar(char byte)

SetSplitChar sets the separator char for hierarchical data access.

func (*Json) SetViolenceCheck

func (j *Json) SetViolenceCheck(enabled bool)

SetViolenceCheck enables/disables violence check for hierarchical data access.

func (*Json) ToIni

func (j *Json) ToIni() ([]byte, error)

ToIni json to ini

func (*Json) ToIniString

func (j *Json) ToIniString() (string, error)

ToIniString ini to string

func (*Json) ToJson

func (j *Json) ToJson() ([]byte, error)

func (*Json) ToJsonIndent

func (j *Json) ToJsonIndent() ([]byte, error)

func (*Json) ToJsonIndentString

func (j *Json) ToJsonIndentString() (string, error)

func (*Json) ToJsonString

func (j *Json) ToJsonString() (string, error)

func (*Json) ToToml

func (j *Json) ToToml() ([]byte, error)

func (*Json) ToTomlString

func (j *Json) ToTomlString() (string, error)

func (*Json) ToXml

func (j *Json) ToXml(rootTag ...string) ([]byte, error)

func (*Json) ToXmlIndent

func (j *Json) ToXmlIndent(rootTag ...string) ([]byte, error)

func (*Json) ToXmlIndentString

func (j *Json) ToXmlIndentString(rootTag ...string) (string, error)

func (*Json) ToXmlString

func (j *Json) ToXmlString(rootTag ...string) (string, error)

func (*Json) ToYaml

func (j *Json) ToYaml() ([]byte, error)

func (*Json) ToYamlString

func (j *Json) ToYamlString() (string, error)

func (*Json) UnmarshalJSON

func (j *Json) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

func (*Json) UnmarshalValue

func (j *Json) UnmarshalValue(value interface{}) error

UnmarshalValue is an interface implement which sets any type of value for Json.

func (*Json) Var

func (j *Json) Var() *gvar.Var

Var returns the json value as *gvar.Var.

type Options

type Options struct {
	Safe      bool   // Mark this object is for in concurrent-safe usage.
	Tags      string // Custom priority tags for decoding.
	StrNumber bool   // StrNumber causes the Decoder to unmarshal a number into an interface{} as a string instead of as a float64.
}

Options for Json object creating.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL