github.com/zhongdalu/gf@v1.0.0/g/encoding/gjson/gjson_api.go (about)

     1  // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gjson
     8  
     9  import (
    10  	"fmt"
    11  	"time"
    12  
    13  	"github.com/zhongdalu/gf/g/util/gutil"
    14  
    15  	"github.com/zhongdalu/gf/g/container/gvar"
    16  	"github.com/zhongdalu/gf/g/os/gtime"
    17  	"github.com/zhongdalu/gf/g/util/gconv"
    18  )
    19  
    20  // Val returns the json value.
    21  func (j *Json) Value() interface{} {
    22  	j.mu.RLock()
    23  	defer j.mu.RUnlock()
    24  	return *(j.p)
    25  }
    26  
    27  // IsNil checks whether the value pointed by <j> is nil.
    28  func (j *Json) IsNil() bool {
    29  	j.mu.RLock()
    30  	defer j.mu.RUnlock()
    31  	return j.p == nil || *(j.p) == nil
    32  }
    33  
    34  // Get returns value by specified <pattern>.
    35  // It returns all values of current Json object, if <pattern> is empty or not specified.
    36  // It returns nil if no value found by <pattern>.
    37  //
    38  // We can also access slice item by its index number in <pattern>,
    39  // eg: "items.name.first", "list.10".
    40  //
    41  // It returns a default value specified by <def> if value for <pattern> is not found.
    42  func (j *Json) Get(pattern string, def ...interface{}) interface{} {
    43  	j.mu.RLock()
    44  	defer j.mu.RUnlock()
    45  
    46  	var result *interface{}
    47  	if j.vc {
    48  		result = j.getPointerByPattern(pattern)
    49  	} else {
    50  		result = j.getPointerByPatternWithoutViolenceCheck(pattern)
    51  	}
    52  	if result != nil {
    53  		return *result
    54  	}
    55  	if len(def) > 0 {
    56  		return def[0]
    57  	}
    58  	return nil
    59  }
    60  
    61  // GetVar returns a *gvar.Var with value by given <pattern>.
    62  func (j *Json) GetVar(pattern string, def ...interface{}) *gvar.Var {
    63  	return gvar.New(j.Get(pattern, def...), true)
    64  }
    65  
    66  // GetMap gets the value by specified <pattern>,
    67  // and converts it to map[string]interface{}.
    68  func (j *Json) GetMap(pattern string, def ...interface{}) map[string]interface{} {
    69  	result := j.Get(pattern, def...)
    70  	if result != nil {
    71  		return gconv.Map(result)
    72  	}
    73  	return nil
    74  }
    75  
    76  // GetJson gets the value by specified <pattern>,
    77  // and converts it to a un-concurrent-safe Json object.
    78  func (j *Json) GetJson(pattern string, def ...interface{}) *Json {
    79  	return New(j.Get(pattern, def...), true)
    80  }
    81  
    82  // GetJsons gets the value by specified <pattern>,
    83  // and converts it to a slice of un-concurrent-safe Json object.
    84  func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json {
    85  	array := j.GetArray(pattern, def...)
    86  	if len(array) > 0 {
    87  		jsonSlice := make([]*Json, len(array))
    88  		for i := 0; i < len(array); i++ {
    89  			jsonSlice[i] = New(array[i], true)
    90  		}
    91  		return jsonSlice
    92  	}
    93  	return nil
    94  }
    95  
    96  // GetJsonMap gets the value by specified <pattern>,
    97  // and converts it to a map of un-concurrent-safe Json object.
    98  func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json {
    99  	m := j.GetMap(pattern, def...)
   100  	if len(m) > 0 {
   101  		jsonMap := make(map[string]*Json, len(m))
   102  		for k, v := range m {
   103  			jsonMap[k] = New(v, true)
   104  		}
   105  		return jsonMap
   106  	}
   107  	return nil
   108  }
   109  
   110  // GetArray gets the value by specified <pattern>,
   111  // and converts it to a slice of []interface{}.
   112  func (j *Json) GetArray(pattern string, def ...interface{}) []interface{} {
   113  	return gconv.Interfaces(j.Get(pattern, def...))
   114  }
   115  
   116  // GetString gets the value by specified <pattern>,
   117  // and converts it to string.
   118  func (j *Json) GetString(pattern string, def ...interface{}) string {
   119  	return gconv.String(j.Get(pattern, def...))
   120  }
   121  
   122  func (j *Json) GetBytes(pattern string, def ...interface{}) []byte {
   123  	return gconv.Bytes(j.Get(pattern, def...))
   124  }
   125  
   126  // GetBool gets the value by specified <pattern>,
   127  // and converts it to bool.
   128  // It returns false when value is: "", 0, false, off, nil;
   129  // or returns true instead.
   130  func (j *Json) GetBool(pattern string, def ...interface{}) bool {
   131  	return gconv.Bool(j.Get(pattern, def...))
   132  }
   133  
   134  func (j *Json) GetInt(pattern string, def ...interface{}) int {
   135  	return gconv.Int(j.Get(pattern, def...))
   136  }
   137  
   138  func (j *Json) GetInt8(pattern string, def ...interface{}) int8 {
   139  	return gconv.Int8(j.Get(pattern, def...))
   140  }
   141  
   142  func (j *Json) GetInt16(pattern string, def ...interface{}) int16 {
   143  	return gconv.Int16(j.Get(pattern, def...))
   144  }
   145  
   146  func (j *Json) GetInt32(pattern string, def ...interface{}) int32 {
   147  	return gconv.Int32(j.Get(pattern, def...))
   148  }
   149  
   150  func (j *Json) GetInt64(pattern string, def ...interface{}) int64 {
   151  	return gconv.Int64(j.Get(pattern, def...))
   152  }
   153  
   154  func (j *Json) GetUint(pattern string, def ...interface{}) uint {
   155  	return gconv.Uint(j.Get(pattern, def...))
   156  }
   157  
   158  func (j *Json) GetUint8(pattern string, def ...interface{}) uint8 {
   159  	return gconv.Uint8(j.Get(pattern, def...))
   160  }
   161  
   162  func (j *Json) GetUint16(pattern string, def ...interface{}) uint16 {
   163  	return gconv.Uint16(j.Get(pattern, def...))
   164  }
   165  
   166  func (j *Json) GetUint32(pattern string, def ...interface{}) uint32 {
   167  	return gconv.Uint32(j.Get(pattern, def...))
   168  }
   169  
   170  func (j *Json) GetUint64(pattern string, def ...interface{}) uint64 {
   171  	return gconv.Uint64(j.Get(pattern, def...))
   172  }
   173  
   174  func (j *Json) GetFloat32(pattern string, def ...interface{}) float32 {
   175  	return gconv.Float32(j.Get(pattern, def...))
   176  }
   177  
   178  func (j *Json) GetFloat64(pattern string, def ...interface{}) float64 {
   179  	return gconv.Float64(j.Get(pattern, def...))
   180  }
   181  
   182  func (j *Json) GetFloats(pattern string, def ...interface{}) []float64 {
   183  	return gconv.Floats(j.Get(pattern, def...))
   184  }
   185  
   186  func (j *Json) GetInts(pattern string, def ...interface{}) []int {
   187  	return gconv.Ints(j.Get(pattern, def...))
   188  }
   189  
   190  // GetStrings gets the value by specified <pattern>,
   191  // and converts it to a slice of []string.
   192  func (j *Json) GetStrings(pattern string, def ...interface{}) []string {
   193  	return gconv.Strings(j.Get(pattern, def...))
   194  }
   195  
   196  // See GetArray.
   197  func (j *Json) GetInterfaces(pattern string, def ...interface{}) []interface{} {
   198  	return gconv.Interfaces(j.Get(pattern, def...))
   199  }
   200  
   201  func (j *Json) GetTime(pattern string, format ...string) time.Time {
   202  	return gconv.Time(j.Get(pattern), format...)
   203  }
   204  
   205  func (j *Json) GetDuration(pattern string, def ...interface{}) time.Duration {
   206  	return gconv.Duration(j.Get(pattern, def...))
   207  }
   208  
   209  func (j *Json) GetGTime(pattern string, format ...string) *gtime.Time {
   210  	return gconv.GTime(j.Get(pattern), format...)
   211  }
   212  
   213  // Set sets value with specified <pattern>.
   214  // It supports hierarchical data access by char separator, which is '.' in default.
   215  func (j *Json) Set(pattern string, value interface{}) error {
   216  	return j.setValue(pattern, value, false)
   217  }
   218  
   219  // Remove deletes value with specified <pattern>.
   220  // It supports hierarchical data access by char separator, which is '.' in default.
   221  func (j *Json) Remove(pattern string) error {
   222  	return j.setValue(pattern, nil, true)
   223  }
   224  
   225  // Contains checks whether the value by specified <pattern> exist.
   226  func (j *Json) Contains(pattern string) bool {
   227  	return j.Get(pattern) != nil
   228  }
   229  
   230  // Len returns the length/size of the value by specified <pattern>.
   231  // The target value by <pattern> should be type of slice or map.
   232  // It returns -1 if the target value is not found, or its type is invalid.
   233  func (j *Json) Len(pattern string) int {
   234  	p := j.getPointerByPattern(pattern)
   235  	if p != nil {
   236  		switch (*p).(type) {
   237  		case map[string]interface{}:
   238  			return len((*p).(map[string]interface{}))
   239  		case []interface{}:
   240  			return len((*p).([]interface{}))
   241  		default:
   242  			return -1
   243  		}
   244  	}
   245  	return -1
   246  }
   247  
   248  // Append appends value to the value by specified <pattern>.
   249  // The target value by <pattern> should be type of slice.
   250  func (j *Json) Append(pattern string, value interface{}) error {
   251  	p := j.getPointerByPattern(pattern)
   252  	if p == nil {
   253  		return j.Set(fmt.Sprintf("%s.0", pattern), value)
   254  	}
   255  	switch (*p).(type) {
   256  	case []interface{}:
   257  		return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]interface{}))), value)
   258  	}
   259  	return fmt.Errorf("invalid variable type of %s", pattern)
   260  }
   261  
   262  // GetToVar gets the value by specified <pattern>,
   263  // and converts it to specified golang variable <v>.
   264  // The <pointer> should be a pointer type.
   265  // Deprecated.
   266  func (j *Json) GetToVar(pattern string, pointer interface{}) error {
   267  	r := j.Get(pattern)
   268  	if r != nil {
   269  		if t, err := Encode(r); err == nil {
   270  			return DecodeTo(t, pointer)
   271  		} else {
   272  			return err
   273  		}
   274  	} else {
   275  		pointer = nil
   276  	}
   277  	return nil
   278  }
   279  
   280  // GetStruct gets the value by specified <pattern>,
   281  // and converts it to specified object <pointer>.
   282  // The <pointer> should be the pointer to an object.
   283  func (j *Json) GetStruct(pattern string, pointer interface{}, mapping ...map[string]string) error {
   284  	return gconv.Struct(j.Get(pattern), pointer, mapping...)
   285  }
   286  
   287  // GetStructDeep does GetStruct recursively.
   288  func (j *Json) GetStructDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
   289  	return gconv.StructDeep(j.Get(pattern), pointer, mapping...)
   290  }
   291  
   292  // GetStructs converts any slice to given struct slice.
   293  func (j *Json) GetStructs(pattern string, pointer interface{}, mapping ...map[string]string) error {
   294  	return gconv.Structs(j.Get(pattern), pointer, mapping...)
   295  }
   296  
   297  // GetStructsDeep converts any slice to given struct slice recursively.
   298  func (j *Json) GetStructsDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
   299  	return gconv.StructsDeep(j.Get(pattern), pointer, mapping...)
   300  }
   301  
   302  // GetToStruct is alias of GetStruct.
   303  // Deprecated.
   304  func (j *Json) GetToStruct(pattern string, pointer interface{}, mapping ...map[string]string) error {
   305  	return j.GetStruct(pattern, pointer, mapping...)
   306  }
   307  
   308  // ToMap converts current Json object to map[string]interface{}.
   309  // It returns nil if fails.
   310  func (j *Json) ToMap() map[string]interface{} {
   311  	j.mu.RLock()
   312  	defer j.mu.RUnlock()
   313  	return gconv.Map(*(j.p))
   314  }
   315  
   316  // ToArray converts current Json object to []interface{}.
   317  // It returns nil if fails.
   318  func (j *Json) ToArray() []interface{} {
   319  	j.mu.RLock()
   320  	defer j.mu.RUnlock()
   321  	return gconv.Interfaces(*(j.p))
   322  }
   323  
   324  // ToStruct converts current Json object to specified object.
   325  // The <pointer> should be a pointer type.
   326  func (j *Json) ToStruct(pointer interface{}) error {
   327  	j.mu.RLock()
   328  	defer j.mu.RUnlock()
   329  	return gconv.Struct(*(j.p), pointer)
   330  }
   331  
   332  func (j *Json) ToStructDeep(pointer interface{}) error {
   333  	j.mu.RLock()
   334  	defer j.mu.RUnlock()
   335  	return gconv.StructDeep(*(j.p), pointer)
   336  }
   337  
   338  func (j *Json) ToStructs(pointer interface{}) error {
   339  	j.mu.RLock()
   340  	defer j.mu.RUnlock()
   341  	return gconv.Structs(*(j.p), pointer)
   342  }
   343  
   344  func (j *Json) ToStructsDeep(pointer interface{}) error {
   345  	j.mu.RLock()
   346  	defer j.mu.RUnlock()
   347  	return gconv.StructsDeep(*(j.p), pointer)
   348  }
   349  
   350  // Dump prints current Json object with more manually readable.
   351  func (j *Json) Dump() {
   352  	j.mu.RLock()
   353  	defer j.mu.RUnlock()
   354  	gutil.Dump(*j.p)
   355  }
   356  
   357  // Export returns <j> as a string with more manually readable.
   358  func (j *Json) Export() string {
   359  	j.mu.RLock()
   360  	defer j.mu.RUnlock()
   361  	return gutil.Export(*j.p)
   362  }