update gjson/gparser

This commit is contained in:
John 2019-05-08 22:04:36 +08:00
parent 8138215597
commit 2b865a55ac
15 changed files with 892 additions and 786 deletions

View File

@ -8,22 +8,12 @@
package gjson
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/gogf/gf/g/encoding/gtoml"
"github.com/gogf/gf/g/encoding/gxml"
"github.com/gogf/gf/g/encoding/gyaml"
"github.com/gogf/gf/g/internal/rwmutex"
"github.com/gogf/gf/g/os/gfcache"
"github.com/gogf/gf/g/text/gregex"
"github.com/gogf/gf/g/text/gstr"
"github.com/gogf/gf/g/util/gconv"
"reflect"
"strconv"
"strings"
"time"
"github.com/gogf/gf/g/internal/rwmutex"
"github.com/gogf/gf/g/text/gstr"
"github.com/gogf/gf/g/util/gconv"
"reflect"
"strconv"
"strings"
)
const (
@ -40,330 +30,6 @@ type Json struct {
// when the hierarchical data key contains separator char.
}
// 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 <unsafe> param specifies whether using this Json object
// in un-concurrent-safe context, which is false in default.
func New(data interface{}, unsafe...bool) *Json {
j := (*Json)(nil)
switch data.(type) {
case map[string]interface{}, []interface{}, nil:
j = &Json {
p : &data,
c : byte(gDEFAULT_SPLIT_CHAR),
vc : false ,
}
case string, []byte:
j, _ = LoadContent(gconv.Bytes(data))
default:
v := (interface{})(nil)
if m := gconv.Map(data); m != nil {
v = m
j = &Json {
p : &v,
c : byte(gDEFAULT_SPLIT_CHAR),
vc : false,
}
} else {
v = gconv.Interfaces(data)
j = &Json {
p : &v,
c : byte(gDEFAULT_SPLIT_CHAR),
vc : false,
}
}
}
j.mu = rwmutex.New(unsafe...)
return j
}
// NewUnsafe creates a un-concurrent-safe Json object.
func NewUnsafe(data...interface{}) *Json {
if len(data) > 0 {
return New(data[0], true)
}
return New(nil, true)
}
// Valid checks whether <data> is a valid JSON data type.
func Valid(data interface{}) bool {
return json.Valid(gconv.Bytes(data))
}
// Encode encodes <value> to JSON data type of bytes.
func Encode(value interface{}) ([]byte, error) {
return json.Marshal(value)
}
// Decode decodes <data>(string/[]byte) to golang variable.
func Decode(data interface{}) (interface{}, error) {
var value interface{}
if err := DecodeTo(gconv.Bytes(data), &value); err != nil {
return nil, err
} else {
return value, nil
}
}
// Decode decodes <data>(string/[]byte) to specified golang variable <v>.
// The <v> should be a pointer type.
func DecodeTo(data interface{}, v interface{}) error {
decoder := json.NewDecoder(bytes.NewReader(gconv.Bytes(data)))
decoder.UseNumber()
return decoder.Decode(v)
}
// DecodeToJson codes <data>(string/[]byte) to a Json object.
func DecodeToJson(data interface{}, unsafe...bool) (*Json, error) {
if v, err := Decode(gconv.Bytes(data)); err != nil {
return nil, err
} else {
return New(v, unsafe...), nil
}
}
// Load loads content from specified file <path>,
// and creates a Json object from its content.
func Load(path string, unsafe...bool) (*Json, error) {
return LoadContent(gfcache.GetBinContents(path), unsafe...)
}
// LoadContent creates a Json object from given content,
// it checks the data type of <content> automatically,
// supporting JSON, XML, YAML and TOML types of data.
func LoadContent(data interface{}, unsafe...bool) (*Json, error) {
var err error
var result interface{}
b := gconv.Bytes(data)
t := "json"
// auto check data type
if json.Valid(b) {
t = "json"
} else if gregex.IsMatch(`^<.+>.*</.+>$`, b) {
t = "xml"
} else if gregex.IsMatch(`^[\s\t]*\w+\s*:\s*.+`, b) || gregex.IsMatch(`\n[\s\t]*\w+\s*:\s*.+`, b) {
t = "yml"
} else if gregex.IsMatch(`^[\s\t]*\w+\s*=\s*.+`, b) || gregex.IsMatch(`\n[\s\t]*\w+\s*=\s*.+`, b) {
t = "toml"
} else {
return nil, errors.New("unsupported data type")
}
// convert to json type data
switch t {
case "json", ".json":
// ok
case "xml", ".xml":
// TODO UseNumber
b, err = gxml.ToJson(b)
case "yml", "yaml", ".yml", ".yaml":
// TODO UseNumber
b, err = gyaml.ToJson(b)
case "toml", ".toml":
// TODO UseNumber
b, err = gtoml.ToJson(b)
default:
err = errors.New("nonsupport type " + t)
}
if err != nil {
return nil, err
}
if result == nil {
decoder := json.NewDecoder(bytes.NewReader(b))
decoder.UseNumber()
if err := decoder.Decode(&result); err != nil {
return nil, err
}
switch result.(type) {
case string, []byte:
return nil, fmt.Errorf(`json decoding failed for content: %s`, string(b))
}
}
return New(result, unsafe...), nil
}
// SetSplitChar sets the separator char for hierarchical data access.
func (j *Json) SetSplitChar(char byte) {
j.mu.Lock()
j.c = char
j.mu.Unlock()
}
// SetViolenceCheck enables/disables violence check for hierarchical data access.
func (j *Json) SetViolenceCheck(enabled bool) {
j.mu.Lock()
j.vc = enabled
j.mu.Unlock()
}
// GetToVar gets the value by specified <pattern>,
// and converts it to specified golang variable <v>.
// The <v> should be a pointer type.
func (j *Json) GetToVar(pattern string, v interface{}) error {
r := j.Get(pattern)
if r != nil {
if t, err := Encode(r); err == nil {
return DecodeTo(t, v)
} else {
return err
}
} else {
v = nil
}
return nil
}
// GetMap gets the value by specified <pattern>,
// and converts it to map[string]interface{}.
func (j *Json) GetMap(pattern string) map[string]interface{} {
result := j.Get(pattern)
if result != nil {
return gconv.Map(result)
}
return nil
}
// GetJson gets the value by specified <pattern>,
// and converts it to a Json object.
func (j *Json) GetJson(pattern string) *Json {
result := j.Get(pattern)
if result != nil {
return New(result)
}
return nil
}
// GetJsons gets the value by specified <pattern>,
// and converts it to a slice of Json object.
func (j *Json) GetJsons(pattern string) []*Json {
array := j.GetArray(pattern)
if len(array) > 0 {
jsons := make([]*Json, len(array))
for i := 0; i < len(array); i++ {
jsons[i] = New(array[i], !j.mu.IsSafe())
}
return jsons
}
return nil
}
// GetArray gets the value by specified <pattern>,
// and converts it to a slice of []interface{}.
func (j *Json) GetArray(pattern string) []interface{} {
return gconv.Interfaces(j.Get(pattern))
}
// GetString gets the value by specified <pattern>,
// and converts it to string.
func (j *Json) GetString(pattern string) string {
return gconv.String(j.Get(pattern))
}
// GetStrings gets the value by specified <pattern>,
// and converts it to a slice of []string.
func (j *Json) GetStrings(pattern string) []string {
return gconv.Strings(j.Get(pattern))
}
// See GetArray.
func (j *Json) GetInterfaces(pattern string) []interface{} {
return gconv.Interfaces(j.Get(pattern))
}
func (j *Json) GetTime(pattern string, format ... string) time.Time {
return gconv.Time(j.Get(pattern), format...)
}
func (j *Json) GetTimeDuration(pattern string) time.Duration {
return gconv.TimeDuration(j.Get(pattern))
}
// GetBool gets the value by specified <pattern>,
// and converts it to bool.
// It returns false when value is: "", 0, false, off, nil;
// or returns true instead.
func (j *Json) GetBool(pattern string) bool {
return gconv.Bool(j.Get(pattern))
}
func (j *Json) GetInt(pattern string) int {
return gconv.Int(j.Get(pattern))
}
func (j *Json) GetInt8(pattern string) int8 {
return gconv.Int8(j.Get(pattern))
}
func (j *Json) GetInt16(pattern string) int16 {
return gconv.Int16(j.Get(pattern))
}
func (j *Json) GetInt32(pattern string) int32 {
return gconv.Int32(j.Get(pattern))
}
func (j *Json) GetInt64(pattern string) int64 {
return gconv.Int64(j.Get(pattern))
}
func (j *Json) GetInts(pattern string) []int {
return gconv.Ints(j.Get(pattern))
}
func (j *Json) GetUint(pattern string) uint {
return gconv.Uint(j.Get(pattern))
}
func (j *Json) GetUint8(pattern string) uint8 {
return gconv.Uint8(j.Get(pattern))
}
func (j *Json) GetUint16(pattern string) uint16 {
return gconv.Uint16(j.Get(pattern))
}
func (j *Json) GetUint32(pattern string) uint32 {
return gconv.Uint32(j.Get(pattern))
}
func (j *Json) GetUint64(pattern string) uint64 {
return gconv.Uint64(j.Get(pattern))
}
func (j *Json) GetFloat32(pattern string) float32 {
return gconv.Float32(j.Get(pattern))
}
func (j *Json) GetFloat64(pattern string) float64 {
return gconv.Float64(j.Get(pattern))
}
func (j *Json) GetFloats(pattern string) []float64 {
return gconv.Floats(j.Get(pattern))
}
// GetToStruct gets the value by specified <pattern>,
// and converts it to specified object <objPointer>.
// The <objPointer> should be the pointer to an object.
func (j *Json) GetToStruct(pattern string, objPointer interface{}) error {
return gconv.Struct(j.Get(pattern), objPointer)
}
// Set sets value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (j *Json) Set(pattern string, value interface{}) error {
return j.setValue(pattern, value, false)
}
// Remove deletes value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (j *Json) Remove(pattern string) error {
return j.setValue(pattern, nil, true)
}
// Set <value> by <pattern>.
// Notice:
// 1. If value is nil and removed is true, means deleting this value;
@ -576,69 +242,6 @@ func (j *Json) setPointerWithValue(pointer *interface{}, key string, value inter
return pointer
}
// Get returns value by specified <pattern>.
// It returns all values of current Json object, if <pattern> is empty or not specified.
// It returns nil if no value found by <pattern>.
//
// We can also access slice item by its index number in <pattern>,
// eg: "items.name.first", "list.10".
func (j *Json) Get(pattern...string) interface{} {
j.mu.RLock()
defer j.mu.RUnlock()
queryPattern := ""
if len(pattern) > 0 {
queryPattern = pattern[0]
}
var result *interface{}
if j.vc {
result = j.getPointerByPattern(queryPattern)
} else {
result = j.getPointerByPatternWithoutViolenceCheck(queryPattern)
}
if result != nil {
return *result
}
return nil
}
// Contains checks whether the value by specified <pattern> exist.
func (j *Json) Contains(pattern...string) bool {
return j.Get(pattern...) != nil
}
// 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 (j *Json) Len(pattern string) int {
p := j.getPointerByPattern(pattern)
if p != nil {
switch (*p).(type) {
case map[string]interface{}:
return len((*p).(map[string]interface{}))
case []interface{}:
return len((*p).([]interface{}))
default:
return -1
}
}
return -1
}
// Append appends value to the value by specified <pattern>.
// The target value by <pattern> should be type of slice.
func (j *Json) Append(pattern string, value interface{}) error {
p := j.getPointerByPattern(pattern)
if p == nil {
return j.Set(fmt.Sprintf("%s.0", pattern), value)
}
switch (*p).(type) {
case []interface{}:
return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]interface{}))), value)
}
return fmt.Errorf("invalid variable type of %s", pattern)
}
// Get a pointer to the value by specified <pattern>.
func (j *Json) getPointerByPattern(pattern string) *interface{} {
if j.vc {
@ -729,111 +332,3 @@ func (j *Json) checkPatternByPointer(key string, pointer *interface{}) *interfac
}
return nil
}
// ToMap converts current Json object to map[string]interface{}.
// It returns nil if fails.
func (j *Json) ToMap() map[string]interface{} {
j.mu.RLock()
defer j.mu.RUnlock()
switch (*(j.p)).(type) {
case map[string]interface{}:
return (*(j.p)).(map[string]interface{})
default:
return nil
}
}
// ToArray converts current Json object to []interface{}.
// It returns nil if fails.
func (j *Json) ToArray() []interface{} {
j.mu.RLock()
defer j.mu.RUnlock()
switch (*(j.p)).(type) {
case []interface{}:
return (*(j.p)).([]interface{})
default:
return nil
}
}
func (j *Json) ToXml(rootTag...string) ([]byte, error) {
return gxml.Encode(j.ToMap(), rootTag...)
}
func (j *Json) ToXmlString(rootTag...string) (string, error) {
b, e := j.ToXml(rootTag...)
return string(b), e
}
func (j *Json) ToXmlIndent(rootTag...string) ([]byte, error) {
return gxml.EncodeWithIndent(j.ToMap(), rootTag...)
}
func (j *Json) ToXmlIndentString(rootTag...string) (string, error) {
b, e := j.ToXmlIndent(rootTag...)
return string(b), e
}
func (j *Json) ToJson() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return Encode(*(j.p))
}
func (j *Json) ToJsonString() (string, error) {
b, e := j.ToJson()
return string(b), e
}
func (j *Json) ToJsonIndent() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return json.MarshalIndent(*(j.p), "", "\t")
}
func (j *Json) ToJsonIndentString() (string, error) {
b, e := j.ToJsonIndent()
return string(b), e
}
func (j *Json) ToYaml() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return gyaml.Encode(*(j.p))
}
func (j *Json) ToYamlString() (string, error) {
b, e := j.ToYaml()
return string(b), e
}
func (j *Json) ToToml() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return gtoml.Encode(*(j.p))
}
func (j *Json) ToTomlString() (string, error) {
b, e := j.ToToml()
return string(b), e
}
// ToStruct converts current Json object to specified object.
// The <objPointer> should be a pointer type.
func (j *Json) ToStruct(objPointer interface{}) error {
j.mu.RLock()
defer j.mu.RUnlock()
return gconv.Struct(*(j.p), objPointer)
}
// Dump prints current Json object with more manually readable.
func (j *Json) Dump() error {
j.mu.RLock()
defer j.mu.RUnlock()
if b, err := j.ToJsonIndent(); err != nil {
return err
} else {
fmt.Println(string(b))
}
return nil
}

View File

@ -0,0 +1,295 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gjson
import (
"fmt"
"github.com/gogf/gf/g/container/gvar"
"github.com/gogf/gf/g/os/gtime"
"github.com/gogf/gf/g/util/gconv"
"time"
)
// Val returns the json value.
func (j *Json) Val() interface{} {
j.mu.RLock()
defer j.mu.RUnlock()
return *(j.p)
}
// Get returns value by specified <pattern>.
// It returns all values of current Json object, if <pattern> is empty or not specified.
// It returns nil if no value found by <pattern>.
//
// We can also access slice item by its index number in <pattern>,
// eg: "items.name.first", "list.10".
func (j *Json) Get(pattern...string) interface{} {
j.mu.RLock()
defer j.mu.RUnlock()
queryPattern := ""
if len(pattern) > 0 {
queryPattern = pattern[0]
}
var result *interface{}
if j.vc {
result = j.getPointerByPattern(queryPattern)
} else {
result = j.getPointerByPatternWithoutViolenceCheck(queryPattern)
}
if result != nil {
return *result
}
return nil
}
// GetVar returns a *gvar.Var with value by given <pattern>.
func (j *Json) GetVar(pattern...string) *gvar.Var {
return gvar.New(j.Get(pattern...), true)
}
// GetMap gets the value by specified <pattern>,
// and converts it to map[string]interface{}.
func (j *Json) GetMap(pattern string) map[string]interface{} {
result := j.Get(pattern)
if result != nil {
return gconv.Map(result)
}
return nil
}
// GetJson gets the value by specified <pattern>,
// and converts it to a Json object.
func (j *Json) GetJson(pattern string) *Json {
result := j.Get(pattern)
if result != nil {
return New(result)
}
return nil
}
// GetJsons gets the value by specified <pattern>,
// and converts it to a slice of Json object.
func (j *Json) GetJsons(pattern string) []*Json {
array := j.GetArray(pattern)
if len(array) > 0 {
jsons := make([]*Json, len(array))
for i := 0; i < len(array); i++ {
jsons[i] = New(array[i], !j.mu.IsSafe())
}
return jsons
}
return nil
}
// GetArray gets the value by specified <pattern>,
// and converts it to a slice of []interface{}.
func (j *Json) GetArray(pattern string) []interface{} {
return gconv.Interfaces(j.Get(pattern))
}
// GetString gets the value by specified <pattern>,
// and converts it to string.
func (j *Json) GetString(pattern string) string {
return gconv.String(j.Get(pattern))
}
// GetBool gets the value by specified <pattern>,
// and converts it to bool.
// It returns false when value is: "", 0, false, off, nil;
// or returns true instead.
func (j *Json) GetBool(pattern string) bool {
return gconv.Bool(j.Get(pattern))
}
func (j *Json) GetInt(pattern string) int {
return gconv.Int(j.Get(pattern))
}
func (j *Json) GetInt8(pattern string) int8 {
return gconv.Int8(j.Get(pattern))
}
func (j *Json) GetInt16(pattern string) int16 {
return gconv.Int16(j.Get(pattern))
}
func (j *Json) GetInt32(pattern string) int32 {
return gconv.Int32(j.Get(pattern))
}
func (j *Json) GetInt64(pattern string) int64 {
return gconv.Int64(j.Get(pattern))
}
func (j *Json) GetInts(pattern string) []int {
return gconv.Ints(j.Get(pattern))
}
func (j *Json) GetUint(pattern string) uint {
return gconv.Uint(j.Get(pattern))
}
func (j *Json) GetUint8(pattern string) uint8 {
return gconv.Uint8(j.Get(pattern))
}
func (j *Json) GetUint16(pattern string) uint16 {
return gconv.Uint16(j.Get(pattern))
}
func (j *Json) GetUint32(pattern string) uint32 {
return gconv.Uint32(j.Get(pattern))
}
func (j *Json) GetUint64(pattern string) uint64 {
return gconv.Uint64(j.Get(pattern))
}
func (j *Json) GetFloat32(pattern string) float32 {
return gconv.Float32(j.Get(pattern))
}
func (j *Json) GetFloat64(pattern string) float64 {
return gconv.Float64(j.Get(pattern))
}
func (j *Json) GetFloats(pattern string) []float64 {
return gconv.Floats(j.Get(pattern))
}
// GetStrings gets the value by specified <pattern>,
// and converts it to a slice of []string.
func (j *Json) GetStrings(pattern string) []string {
return gconv.Strings(j.Get(pattern))
}
// See GetArray.
func (j *Json) GetInterfaces(pattern string) []interface{} {
return gconv.Interfaces(j.Get(pattern))
}
func (j *Json) GetTime(pattern string, format ... string) time.Time {
return gconv.Time(j.Get(pattern), format...)
}
func (j *Json) GetTimeDuration(pattern string) time.Duration {
return gconv.TimeDuration(j.Get(pattern))
}
func (j *Json) GetGTime(pattern string) *gtime.Time {
return gconv.GTime(j.Get(pattern))
}
// Set sets value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (j *Json) Set(pattern string, value interface{}) error {
return j.setValue(pattern, value, false)
}
// Remove deletes value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (j *Json) Remove(pattern string) error {
return j.setValue(pattern, nil, true)
}
// Contains checks whether the value by specified <pattern> exist.
func (j *Json) Contains(pattern string) bool {
return j.Get(pattern) != nil
}
// 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 (j *Json) Len(pattern string) int {
p := j.getPointerByPattern(pattern)
if p != nil {
switch (*p).(type) {
case map[string]interface{}:
return len((*p).(map[string]interface{}))
case []interface{}:
return len((*p).([]interface{}))
default:
return -1
}
}
return -1
}
// Append appends value to the value by specified <pattern>.
// The target value by <pattern> should be type of slice.
func (j *Json) Append(pattern string, value interface{}) error {
p := j.getPointerByPattern(pattern)
if p == nil {
return j.Set(fmt.Sprintf("%s.0", pattern), value)
}
switch (*p).(type) {
case []interface{}:
return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]interface{}))), value)
}
return fmt.Errorf("invalid variable type of %s", pattern)
}
// GetToVar gets the value by specified <pattern>,
// and converts it to specified golang variable <v>.
// The <v> should be a pointer type.
func (j *Json) GetToVar(pattern string, v interface{}) error {
r := j.Get(pattern)
if r != nil {
if t, err := Encode(r); err == nil {
return DecodeTo(t, v)
} else {
return err
}
} else {
v = nil
}
return nil
}
// GetToStruct gets the value by specified <pattern>,
// and converts it to specified object <objPointer>.
// The <objPointer> should be the pointer to an object.
func (j *Json) GetToStruct(pattern string, objPointer interface{}) error {
return gconv.Struct(j.Get(pattern), objPointer)
}
// ToMap converts current Json object to map[string]interface{}.
// It returns nil if fails.
func (j *Json) ToMap() map[string]interface{} {
j.mu.RLock()
defer j.mu.RUnlock()
return gconv.Map(*(j.p))
}
// ToArray converts current Json object to []interface{}.
// It returns nil if fails.
func (j *Json) ToArray() []interface{} {
j.mu.RLock()
defer j.mu.RUnlock()
return gconv.Interfaces(*(j.p))
}
// ToStruct converts current Json object to specified object.
// The <objPointer> should be a pointer type.
func (j *Json) ToStruct(pointer interface{}) error {
j.mu.RLock()
defer j.mu.RUnlock()
return gconv.Struct(*(j.p), pointer)
}
// Dump prints current Json object with more manually readable.
func (j *Json) Dump() error {
j.mu.RLock()
defer j.mu.RUnlock()
if b, err := j.ToJsonIndent(); err != nil {
return err
} else {
fmt.Println(string(b))
}
return nil
}

View File

@ -0,0 +1,21 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gjson
// SetSplitChar sets the separator char for hierarchical data access.
func (j *Json) SetSplitChar(char byte) {
j.mu.Lock()
j.c = char
j.mu.Unlock()
}
// SetViolenceCheck enables/disables violence check for hierarchical data access.
func (j *Json) SetViolenceCheck(enabled bool) {
j.mu.Lock()
j.vc = enabled
j.mu.Unlock()
}

View File

@ -0,0 +1,76 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gjson
import (
"encoding/json"
"github.com/gogf/gf/g/encoding/gtoml"
"github.com/gogf/gf/g/encoding/gxml"
"github.com/gogf/gf/g/encoding/gyaml"
)
func (j *Json) ToXml(rootTag...string) ([]byte, error) {
return gxml.Encode(j.ToMap(), rootTag...)
}
func (j *Json) ToXmlString(rootTag...string) (string, error) {
b, e := j.ToXml(rootTag...)
return string(b), e
}
func (j *Json) ToXmlIndent(rootTag...string) ([]byte, error) {
return gxml.EncodeWithIndent(j.ToMap(), rootTag...)
}
func (j *Json) ToXmlIndentString(rootTag...string) (string, error) {
b, e := j.ToXmlIndent(rootTag...)
return string(b), e
}
func (j *Json) ToJson() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return Encode(*(j.p))
}
func (j *Json) ToJsonString() (string, error) {
b, e := j.ToJson()
return string(b), e
}
func (j *Json) ToJsonIndent() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return json.MarshalIndent(*(j.p), "", "\t")
}
func (j *Json) ToJsonIndentString() (string, error) {
b, e := j.ToJsonIndent()
return string(b), e
}
func (j *Json) ToYaml() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return gyaml.Encode(*(j.p))
}
func (j *Json) ToYamlString() (string, error) {
b, e := j.ToYaml()
return string(b), e
}
func (j *Json) ToToml() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return gtoml.Encode(*(j.p))
}
func (j *Json) ToTomlString() (string, error) {
b, e := j.ToToml()
return string(b), e
}

View File

@ -0,0 +1,167 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package gjson provides convenient API for JSON/XML/YAML/TOML data handling.
package gjson
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/gogf/gf/g/encoding/gtoml"
"github.com/gogf/gf/g/encoding/gxml"
"github.com/gogf/gf/g/encoding/gyaml"
"github.com/gogf/gf/g/internal/rwmutex"
"github.com/gogf/gf/g/os/gfcache"
"github.com/gogf/gf/g/text/gregex"
"github.com/gogf/gf/g/util/gconv"
)
// 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 <unsafe> param specifies whether using this Json object
// in un-concurrent-safe context, which is false in default.
func New(data interface{}, unsafe...bool) *Json {
j := (*Json)(nil)
switch data.(type) {
case map[string]interface{}, []interface{}, nil:
j = &Json {
p : &data,
c : byte(gDEFAULT_SPLIT_CHAR),
vc : false ,
}
case string, []byte:
j, _ = LoadContent(gconv.Bytes(data))
default:
v := (interface{})(nil)
if m := gconv.Map(data); m != nil {
v = m
j = &Json {
p : &v,
c : byte(gDEFAULT_SPLIT_CHAR),
vc : false,
}
} else {
v = gconv.Interfaces(data)
j = &Json {
p : &v,
c : byte(gDEFAULT_SPLIT_CHAR),
vc : false,
}
}
}
j.mu = rwmutex.New(unsafe...)
return j
}
// NewUnsafe creates a un-concurrent-safe Json object.
func NewUnsafe(data...interface{}) *Json {
if len(data) > 0 {
return New(data[0], true)
}
return New(nil, true)
}
// Valid checks whether <data> is a valid JSON data type.
func Valid(data interface{}) bool {
return json.Valid(gconv.Bytes(data))
}
// Encode encodes <value> to JSON data type of bytes.
func Encode(value interface{}) ([]byte, error) {
return json.Marshal(value)
}
// Decode decodes <data>(string/[]byte) to golang variable.
func Decode(data interface{}) (interface{}, error) {
var value interface{}
if err := DecodeTo(gconv.Bytes(data), &value); err != nil {
return nil, err
} else {
return value, nil
}
}
// Decode decodes <data>(string/[]byte) to specified golang variable <v>.
// The <v> should be a pointer type.
func DecodeTo(data interface{}, v interface{}) error {
decoder := json.NewDecoder(bytes.NewReader(gconv.Bytes(data)))
decoder.UseNumber()
return decoder.Decode(v)
}
// DecodeToJson codes <data>(string/[]byte) to a Json object.
func DecodeToJson(data interface{}, unsafe...bool) (*Json, error) {
if v, err := Decode(gconv.Bytes(data)); err != nil {
return nil, err
} else {
return New(v, unsafe...), nil
}
}
// Load loads content from specified file <path>,
// and creates a Json object from its content.
func Load(path string, unsafe...bool) (*Json, error) {
return LoadContent(gfcache.GetBinContents(path), unsafe...)
}
// LoadContent creates a Json object from given content,
// it checks the data type of <content> automatically,
// supporting JSON, XML, YAML and TOML types of data.
func LoadContent(data interface{}, unsafe...bool) (*Json, error) {
var err error
var result interface{}
b := gconv.Bytes(data)
t := "json"
// auto check data type
if json.Valid(b) {
t = "json"
} else if gregex.IsMatch(`^<.+>.*</.+>$`, b) {
t = "xml"
} else if gregex.IsMatch(`^[\s\t]*\w+\s*:\s*.+`, b) || gregex.IsMatch(`\n[\s\t]*\w+\s*:\s*.+`, b) {
t = "yml"
} else if gregex.IsMatch(`^[\s\t]*\w+\s*=\s*.+`, b) || gregex.IsMatch(`\n[\s\t]*\w+\s*=\s*.+`, b) {
t = "toml"
} else {
return nil, errors.New("unsupported data type")
}
// convert to json type data
switch t {
case "json", ".json":
// ok
case "xml", ".xml":
// TODO UseNumber
b, err = gxml.ToJson(b)
case "yml", "yaml", ".yml", ".yaml":
// TODO UseNumber
b, err = gyaml.ToJson(b)
case "toml", ".toml":
// TODO UseNumber
b, err = gtoml.ToJson(b)
default:
err = errors.New("nonsupport type " + t)
}
if err != nil {
return nil, err
}
if result == nil {
decoder := json.NewDecoder(bytes.NewReader(b))
decoder.UseNumber()
if err := decoder.Decode(&result); err != nil {
return nil, err
}
switch result.(type) {
case string, []byte:
return nil, fmt.Errorf(`json decoding failed for content: %s`, string(b))
}
}
return New(result, unsafe...), nil
}

View File

@ -8,283 +8,10 @@
package gparser
import (
"github.com/gogf/gf/g/encoding/gjson"
"time"
"github.com/gogf/gf/g/encoding/gjson"
)
type Parser struct {
json *gjson.Json
}
// New creates a Parser 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 <unsafe> param specifies whether using this Parser object
// in un-concurrent-safe context, which is false in default.
func New(value interface{}, unsafe...bool) *Parser {
return &Parser{gjson.New(value, unsafe...)}
}
// NewUnsafe creates a un-concurrent-safe Parser object.
func NewUnsafe (value...interface{}) *Parser {
if len(value) > 0 {
return &Parser{gjson.New(value[0], false)}
}
return &Parser{gjson.New(nil, false)}
}
// Load loads content from specified file <path>,
// and creates a Parser object from its content.
func Load (path string, unsafe...bool) (*Parser, error) {
if j, e := gjson.Load(path, unsafe...); e == nil {
return &Parser{j}, nil
} else {
return nil, e
}
}
// LoadContent creates a Parser object from given content,
// it checks the data type of <content> automatically,
// supporting JSON, XML, YAML and TOML types of data.
func LoadContent (data []byte, unsafe...bool) (*Parser, error) {
if j, e := gjson.LoadContent(data, unsafe...); e == nil {
return &Parser{j}, nil
} else {
return nil, e
}
}
// SetSplitChar sets the separator char for hierarchical data access.
func (p *Parser) SetSplitChar(char byte) {
p.json.SetSplitChar(char)
}
// SetViolenceCheck enables/disables violence check for hierarchical data access.
func (p *Parser) SetViolenceCheck(check bool) {
p.json.SetViolenceCheck(check)
}
// GetToVar gets the value by specified <pattern>,
// and converts it to specified golang variable <v>.
// The <v> should be a pointer type.
func (p *Parser) GetToVar(pattern string, v interface{}) error {
return p.json.GetToVar(pattern, v)
}
// GetMap gets the value by specified <pattern>,
// and converts it to map[string]interface{}.
func (p *Parser) GetMap(pattern string) map[string]interface{} {
return p.json.GetMap(pattern)
}
// GetArray gets the value by specified <pattern>,
// and converts it to a slice of []interface{}.
func (p *Parser) GetArray(pattern string) []interface{} {
return p.json.GetArray(pattern)
}
// GetString gets the value by specified <pattern>,
// and converts it to string.
func (p *Parser) GetString(pattern string) string {
return p.json.GetString(pattern)
}
// GetStrings gets the value by specified <pattern>,
// and converts it to a slice of []string.
func (p *Parser) GetStrings(pattern string) []string {
return p.json.GetStrings(pattern)
}
func (p *Parser) GetInterfaces(pattern string) []interface{} {
return p.json.GetInterfaces(pattern)
}
func (p *Parser) GetTime(pattern string, format ... string) time.Time {
return p.json.GetTime(pattern, format...)
}
func (p *Parser) GetTimeDuration(pattern string) time.Duration {
return p.json.GetTimeDuration(pattern)
}
// GetBool gets the value by specified <pattern>,
// and converts it to bool.
// It returns false when value is: "", 0, false, off, nil;
// or returns true instead.
func (p *Parser) GetBool(pattern string) bool {
return p.json.GetBool(pattern)
}
func (p *Parser) GetInt(pattern string) int {
return p.json.GetInt(pattern)
}
func (p *Parser) GetInt8(pattern string) int8 {
return p.json.GetInt8(pattern)
}
func (p *Parser) GetInt16(pattern string) int16 {
return p.json.GetInt16(pattern)
}
func (p *Parser) GetInt32(pattern string) int32 {
return p.json.GetInt32(pattern)
}
func (p *Parser) GetInt64(pattern string) int64 {
return p.json.GetInt64(pattern)
}
func (p *Parser) GetInts(pattern string) []int {
return p.json.GetInts(pattern)
}
func (p *Parser) GetUint(pattern string) uint {
return p.json.GetUint(pattern)
}
func (p *Parser) GetUint8(pattern string) uint8 {
return p.json.GetUint8(pattern)
}
func (p *Parser) GetUint16(pattern string) uint16 {
return p.json.GetUint16(pattern)
}
func (p *Parser) GetUint32(pattern string) uint32 {
return p.json.GetUint32(pattern)
}
func (p *Parser) GetUint64(pattern string) uint64 {
return p.json.GetUint64(pattern)
}
func (p *Parser) GetFloat32(pattern string) float32 {
return p.json.GetFloat32(pattern)
}
func (p *Parser) GetFloat64(pattern string) float64 {
return p.json.GetFloat64(pattern)
}
func (p *Parser) GetFloats(pattern string) []float64 {
return p.json.GetFloats(pattern)
}
// GetToStruct gets the value by specified <pattern>,
// and converts it to specified object <objPointer>.
// The <objPointer> should be the pointer to an object.
func (p *Parser) GetToStruct(pattern string, objPointer interface{}) error {
return p.json.GetToStruct(pattern, objPointer)
}
// Set sets value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (p *Parser) Set(pattern string, value interface{}) error {
return p.json.Set(pattern, value)
}
// 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 (p *Parser) Len(pattern string) int {
return p.json.Len(pattern)
}
// Append appends value to the value by specified <pattern>.
// The target value by <pattern> should be type of slice.
func (p *Parser) Append(pattern string, value interface{}) error {
return p.json.Append(pattern, value)
}
// Remove deletes value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (p *Parser) Remove(pattern string) error {
return p.json.Remove(pattern)
}
// Get returns value by specified <pattern>.
// It returns all values of current Json object, if <pattern> is empty or not specified.
// It returns nil if no value found by <pattern>.
//
// We can also access slice item by its index number in <pattern>,
// eg: "items.name.first", "list.10".
func (p *Parser) Get(pattern...string) interface{} {
return p.json.Get(pattern...)
}
// ToMap converts current object values to map[string]interface{}.
// It returns nil if fails.
func (p *Parser) ToMap() map[string]interface{} {
return p.json.ToMap()
}
// ToArray converts current object values to []interface{}.
// It returns nil if fails.
func (p *Parser) ToArray() []interface{} {
return p.json.ToArray()
}
func (p *Parser) ToXml(rootTag...string) ([]byte, error) {
return p.json.ToXml(rootTag...)
}
func (p *Parser) ToXmlIndent(rootTag...string) ([]byte, error) {
return p.json.ToXmlIndent(rootTag...)
}
func (p *Parser) ToJson() ([]byte, error) {
return p.json.ToJson()
}
func (p *Parser) ToJsonIndent() ([]byte, error) {
return p.json.ToJsonIndent()
}
func (p *Parser) ToYaml() ([]byte, error) {
return p.json.ToYaml()
}
func (p *Parser) ToToml() ([]byte, error) {
return p.json.ToToml()
}
// Dump prints current Json object with more manually readable.
func (p *Parser) Dump() error {
return p.json.Dump()
}
// ToStruct converts current Json object to specified object.
// The <objPointer> should be a pointer type.
func (p *Parser) ToStruct(o interface{}) error {
return p.json.ToStruct(o)
}
func VarToXml(value interface{}, rootTag...string) ([]byte, error) {
return New(value).ToXml(rootTag...)
}
func VarToXmlIndent(value interface{}, rootTag...string) ([]byte, error) {
return New(value).ToXmlIndent(rootTag...)
}
func VarToJson(value interface{}) ([]byte, error) {
return New(value).ToJson()
}
func VarToJsonIndent(value interface{}) ([]byte, error) {
return New(value).ToJsonIndent()
}
func VarToYaml(value interface{}) ([]byte, error) {
return New(value).ToYaml()
}
func VarToToml(value interface{}) ([]byte, error) {
return New(value).ToToml()
}
func VarToStruct(value interface{}, obj interface{}) error {
return New(value).ToStruct(obj)
}

View File

@ -0,0 +1,199 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gp.
package gparser
import (
"github.com/gogf/gf/g/container/gvar"
"github.com/gogf/gf/g/os/gtime"
"time"
)
// Val returns the value.
func (p *Parser) Val() interface{} {
return p.json.Val()
}
// Get returns value by specified <pattern>.
// It returns all values of current Json object, if <pattern> is empty or not specified.
// It returns nil if no value found by <pattern>.
//
// We can also access slice item by its index number in <pattern>,
// eg: "items.name.first", "list.10".
func (p *Parser) Get(pattern...string) interface{} {
return p.json.Get(pattern...)
}
// GetVar returns a *gvar.Var with value by given <pattern>.
func (p *Parser) GetVar(pattern...string) *gvar.Var {
return p.json.GetVar(pattern...)
}
// GetMap gets the value by specified <pattern>,
// and converts it to map[string]interface{}.
func (p *Parser) GetMap(pattern string) map[string]interface{} {
return p.json.GetMap(pattern)
}
// GetArray gets the value by specified <pattern>,
// and converts it to a slice of []interface{}.
func (p *Parser) GetArray(pattern string) []interface{} {
return p.json.GetArray(pattern)
}
// GetString gets the value by specified <pattern>,
// and converts it to string.
func (p *Parser) GetString(pattern string) string {
return p.json.GetString(pattern)
}
// GetBool gets the value by specified <pattern>,
// and converts it to bool.
// It returns false when value is: "", 0, false, off, nil;
// or returns true instead.
func (p *Parser) GetBool(pattern string) bool {
return p.json.GetBool(pattern)
}
func (p *Parser) GetInt(pattern string) int {
return p.json.GetInt(pattern)
}
func (p *Parser) GetInt8(pattern string) int8 {
return p.json.GetInt8(pattern)
}
func (p *Parser) GetInt16(pattern string) int16 {
return p.json.GetInt16(pattern)
}
func (p *Parser) GetInt32(pattern string) int32 {
return p.json.GetInt32(pattern)
}
func (p *Parser) GetInt64(pattern string) int64 {
return p.json.GetInt64(pattern)
}
func (p *Parser) GetInts(pattern string) []int {
return p.json.GetInts(pattern)
}
func (p *Parser) GetUint(pattern string) uint {
return p.json.GetUint(pattern)
}
func (p *Parser) GetUint8(pattern string) uint8 {
return p.json.GetUint8(pattern)
}
func (p *Parser) GetUint16(pattern string) uint16 {
return p.json.GetUint16(pattern)
}
func (p *Parser) GetUint32(pattern string) uint32 {
return p.json.GetUint32(pattern)
}
func (p *Parser) GetUint64(pattern string) uint64 {
return p.json.GetUint64(pattern)
}
func (p *Parser) GetFloat32(pattern string) float32 {
return p.json.GetFloat32(pattern)
}
func (p *Parser) GetFloat64(pattern string) float64 {
return p.json.GetFloat64(pattern)
}
func (p *Parser) GetFloats(pattern string) []float64 {
return p.json.GetFloats(pattern)
}
// GetStrings gets the value by specified <pattern>,
// and converts it to a slice of []string.
func (p *Parser) GetStrings(pattern string) []string {
return p.json.GetStrings(pattern)
}
func (p *Parser) GetInterfaces(pattern string) []interface{} {
return p.json.GetInterfaces(pattern)
}
func (p *Parser) GetTime(pattern string, format ... string) time.Time {
return p.json.GetTime(pattern, format...)
}
func (p *Parser) GetTimeDuration(pattern string) time.Duration {
return p.json.GetTimeDuration(pattern)
}
func (p *Parser) GetGTime(pattern string) *gtime.Time {
return p.json.GetGTime(pattern)
}
// GetToVar gets the value by specified <pattern>,
// and converts it to specified golang variable <v>.
// The <v> should be a pointer type.
func (p *Parser) GetToVar(pattern string, v interface{}) error {
return p.json.GetToVar(pattern, v)
}
// GetToStruct gets the value by specified <pattern>,
// and converts it to specified object <objPointer>.
// The <objPointer> should be the pointer to an object.
func (p *Parser) GetToStruct(pattern string, objPointer interface{}) error {
return p.json.GetToStruct(pattern, objPointer)
}
// Set sets value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (p *Parser) Set(pattern string, value interface{}) error {
return p.json.Set(pattern, value)
}
// 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 (p *Parser) Len(pattern string) int {
return p.json.Len(pattern)
}
// Append appends value to the value by specified <pattern>.
// The target value by <pattern> should be type of slice.
func (p *Parser) Append(pattern string, value interface{}) error {
return p.json.Append(pattern, value)
}
// Remove deletes value with specified <pattern>.
// It supports hierarchical data access by char separator, which is '.' in default.
func (p *Parser) Remove(pattern string) error {
return p.json.Remove(pattern)
}
// ToMap converts current object values to map[string]interface{}.
// It returns nil if fails.
func (p *Parser) ToMap() map[string]interface{} {
return p.json.ToMap()
}
// ToArray converts current object values to []interface{}.
// It returns nil if fails.
func (p *Parser) ToArray() []interface{} {
return p.json.ToArray()
}
// ToStruct converts current Json object to specified object.
// The <objPointer> should be a pointer type.
func (p *Parser) ToStruct(pointer interface{}) error {
return p.json.ToStruct(pointer)
}
// Dump prints current Json object with more manually readable.
func (p *Parser) Dump() error {
return p.json.Dump()
}

View File

@ -0,0 +1,17 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gp.
package gparser
// SetSplitChar sets the separator char for hierarchical data access.
func (p *Parser) SetSplitChar(char byte) {
p.json.SetSplitChar(char)
}
// SetViolenceCheck enables/disables violence check for hierarchical data access.
func (p *Parser) SetViolenceCheck(check bool) {
p.json.SetViolenceCheck(check)
}

View File

@ -0,0 +1,60 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gp.
package gparser
func (p *Parser) ToXml(rootTag...string) ([]byte, error) {
return p.json.ToXml(rootTag...)
}
func (p *Parser) ToXmlIndent(rootTag...string) ([]byte, error) {
return p.json.ToXmlIndent(rootTag...)
}
func (p *Parser) ToJson() ([]byte, error) {
return p.json.ToJson()
}
func (p *Parser) ToJsonIndent() ([]byte, error) {
return p.json.ToJsonIndent()
}
func (p *Parser) ToYaml() ([]byte, error) {
return p.json.ToYaml()
}
func (p *Parser) ToToml() ([]byte, error) {
return p.json.ToToml()
}
func VarToXml(value interface{}, rootTag...string) ([]byte, error) {
return New(value).ToXml(rootTag...)
}
func VarToXmlIndent(value interface{}, rootTag...string) ([]byte, error) {
return New(value).ToXmlIndent(rootTag...)
}
func VarToJson(value interface{}) ([]byte, error) {
return New(value).ToJson()
}
func VarToJsonIndent(value interface{}) ([]byte, error) {
return New(value).ToJsonIndent()
}
func VarToYaml(value interface{}) ([]byte, error) {
return New(value).ToYaml()
}
func VarToToml(value interface{}) ([]byte, error) {
return New(value).ToToml()
}
func VarToStruct(value interface{}, obj interface{}) error {
return New(value).ToStruct(obj)
}

View File

@ -0,0 +1,49 @@
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gp.
package gparser
import (
"github.com/gogf/gf/g/encoding/gjson"
)
// New creates a Parser 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 <unsafe> param specifies whether using this Parser object
// in un-concurrent-safe context, which is false in default.
func New(value interface{}, unsafe...bool) *Parser {
return &Parser{gjson.New(value, unsafe...)}
}
// NewUnsafe creates a un-concurrent-safe Parser object.
func NewUnsafe (value...interface{}) *Parser {
if len(value) > 0 {
return &Parser{gjson.New(value[0], false)}
}
return &Parser{gjson.New(nil, false)}
}
// Load loads content from specified file <path>,
// and creates a Parser object from its content.
func Load (path string, unsafe...bool) (*Parser, error) {
if j, e := gjson.Load(path, unsafe...); e == nil {
return &Parser{j}, nil
} else {
return nil, e
}
}
// LoadContent creates a Parser object from given content,
// it checks the data type of <content> automatically,
// supporting JSON, XML, YAML and TOML types of data.
func LoadContent (data []byte, unsafe...bool) (*Parser, error) {
if j, e := gjson.LoadContent(data, unsafe...); e == nil {
return &Parser{j}, nil
} else {
return nil, e
}
}

View File

@ -4,7 +4,7 @@
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package gcfg provides reading, caching and managing for configuration files/contents.
// Package gcfg provides reading, caching and managing for configuration.
package gcfg
import (