github.com/gogf/gf@v1.16.9/encoding/gjson/gjson_api.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). 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/gogf/gf.
     6  
     7  package gjson
     8  
     9  import (
    10  	"fmt"
    11  	"time"
    12  
    13  	"github.com/gogf/gf/util/gutil"
    14  
    15  	"github.com/gogf/gf/container/gvar"
    16  	"github.com/gogf/gf/os/gtime"
    17  	"github.com/gogf/gf/util/gconv"
    18  )
    19  
    20  // Value returns the json value.
    21  // Deprecated, use Interface instead.
    22  func (j *Json) Value() interface{} {
    23  	return j.Interface()
    24  }
    25  
    26  // Interface returns the json value.
    27  func (j *Json) Interface() interface{} {
    28  	j.mu.RLock()
    29  	defer j.mu.RUnlock()
    30  	return *(j.p)
    31  }
    32  
    33  // Var returns the json value as *gvar.Var.
    34  func (j *Json) Var() *gvar.Var {
    35  	return gvar.New(j.Value())
    36  }
    37  
    38  // IsNil checks whether the value pointed by <j> is nil.
    39  func (j *Json) IsNil() bool {
    40  	j.mu.RLock()
    41  	defer j.mu.RUnlock()
    42  	return j.p == nil || *(j.p) == nil
    43  }
    44  
    45  // Get retrieves and returns value by specified <pattern>.
    46  // It returns all values of current Json object if <pattern> is given empty or string ".".
    47  // It returns nil if no value found by <pattern>.
    48  //
    49  // We can also access slice item by its index number in <pattern> like:
    50  // "list.10", "array.0.name", "array.0.1.id".
    51  //
    52  // It returns a default value specified by <def> if value for <pattern> is not found.
    53  func (j *Json) Get(pattern string, def ...interface{}) interface{} {
    54  	j.mu.RLock()
    55  	defer j.mu.RUnlock()
    56  
    57  	// It returns nil if pattern is empty.
    58  	if pattern == "" {
    59  		return nil
    60  	}
    61  
    62  	// It returns all if pattern is ".".
    63  	if pattern == "." {
    64  		return *j.p
    65  	}
    66  
    67  	var result *interface{}
    68  	if j.vc {
    69  		result = j.getPointerByPattern(pattern)
    70  	} else {
    71  		result = j.getPointerByPatternWithoutViolenceCheck(pattern)
    72  	}
    73  	if result != nil {
    74  		return *result
    75  	}
    76  	if len(def) > 0 {
    77  		return def[0]
    78  	}
    79  	return nil
    80  }
    81  
    82  // GetVar returns a gvar.Var with value by given <pattern>.
    83  func (j *Json) GetVar(pattern string, def ...interface{}) *gvar.Var {
    84  	return gvar.New(j.Get(pattern, def...))
    85  }
    86  
    87  // GetVars returns []*gvar.Var with value by given <pattern>.
    88  func (j *Json) GetVars(pattern string, def ...interface{}) []*gvar.Var {
    89  	return gvar.New(j.Get(pattern, def...)).Vars()
    90  }
    91  
    92  // GetMap retrieves and returns the value by specified <pattern> as map[string]interface{}.
    93  func (j *Json) GetMap(pattern string, def ...interface{}) map[string]interface{} {
    94  	result := j.Get(pattern, def...)
    95  	if result != nil {
    96  		return gconv.Map(result)
    97  	}
    98  	return nil
    99  }
   100  
   101  // GetMapStrStr retrieves and returns the value by specified <pattern> as map[string]string.
   102  func (j *Json) GetMapStrStr(pattern string, def ...interface{}) map[string]string {
   103  	result := j.Get(pattern, def...)
   104  	if result != nil {
   105  		return gconv.MapStrStr(result)
   106  	}
   107  	return nil
   108  }
   109  
   110  // GetMaps retrieves and returns the value by specified <pattern> as []map[string]interface{}.
   111  func (j *Json) GetMaps(pattern string, def ...interface{}) []map[string]interface{} {
   112  	result := j.Get(pattern, def...)
   113  	if result != nil {
   114  		return gconv.Maps(result)
   115  	}
   116  	return nil
   117  }
   118  
   119  // GetJson gets the value by specified <pattern>,
   120  // and converts it to a un-concurrent-safe Json object.
   121  func (j *Json) GetJson(pattern string, def ...interface{}) *Json {
   122  	return New(j.Get(pattern, def...))
   123  }
   124  
   125  // GetJsons gets the value by specified <pattern>,
   126  // and converts it to a slice of un-concurrent-safe Json object.
   127  func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json {
   128  	array := j.GetArray(pattern, def...)
   129  	if len(array) > 0 {
   130  		jsonSlice := make([]*Json, len(array))
   131  		for i := 0; i < len(array); i++ {
   132  			jsonSlice[i] = New(array[i])
   133  		}
   134  		return jsonSlice
   135  	}
   136  	return nil
   137  }
   138  
   139  // GetJsonMap gets the value by specified <pattern>,
   140  // and converts it to a map of un-concurrent-safe Json object.
   141  func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json {
   142  	m := j.GetMap(pattern, def...)
   143  	if len(m) > 0 {
   144  		jsonMap := make(map[string]*Json, len(m))
   145  		for k, v := range m {
   146  			jsonMap[k] = New(v)
   147  		}
   148  		return jsonMap
   149  	}
   150  	return nil
   151  }
   152  
   153  // GetArray retrieves the value by specified <pattern>,
   154  // and converts it to a slice of []interface{}.
   155  func (j *Json) GetArray(pattern string, def ...interface{}) []interface{} {
   156  	return gconv.Interfaces(j.Get(pattern, def...))
   157  }
   158  
   159  // GetString retrieves the value by specified <pattern> and converts it to string.
   160  func (j *Json) GetString(pattern string, def ...interface{}) string {
   161  	return gconv.String(j.Get(pattern, def...))
   162  }
   163  
   164  // GetBytes retrieves the value by specified <pattern> and converts it to []byte.
   165  func (j *Json) GetBytes(pattern string, def ...interface{}) []byte {
   166  	return gconv.Bytes(j.Get(pattern, def...))
   167  }
   168  
   169  // GetBool retrieves the value by specified <pattern>,
   170  // converts and returns it as bool.
   171  // It returns false when value is: "", 0, false, off, nil;
   172  // or returns true instead.
   173  func (j *Json) GetBool(pattern string, def ...interface{}) bool {
   174  	return gconv.Bool(j.Get(pattern, def...))
   175  }
   176  
   177  // GetInt retrieves the value by specified <pattern> and converts it to int.
   178  func (j *Json) GetInt(pattern string, def ...interface{}) int {
   179  	return gconv.Int(j.Get(pattern, def...))
   180  }
   181  
   182  // GetInt8 retrieves the value by specified <pattern> and converts it to int8.
   183  func (j *Json) GetInt8(pattern string, def ...interface{}) int8 {
   184  	return gconv.Int8(j.Get(pattern, def...))
   185  }
   186  
   187  // GetInt16 retrieves the value by specified <pattern> and converts it to int16.
   188  func (j *Json) GetInt16(pattern string, def ...interface{}) int16 {
   189  	return gconv.Int16(j.Get(pattern, def...))
   190  }
   191  
   192  // GetInt32 retrieves the value by specified <pattern> and converts it to int32.
   193  func (j *Json) GetInt32(pattern string, def ...interface{}) int32 {
   194  	return gconv.Int32(j.Get(pattern, def...))
   195  }
   196  
   197  // GetInt64 retrieves the value by specified <pattern> and converts it to int64.
   198  func (j *Json) GetInt64(pattern string, def ...interface{}) int64 {
   199  	return gconv.Int64(j.Get(pattern, def...))
   200  }
   201  
   202  // GetUint retrieves the value by specified <pattern> and converts it to uint.
   203  func (j *Json) GetUint(pattern string, def ...interface{}) uint {
   204  	return gconv.Uint(j.Get(pattern, def...))
   205  }
   206  
   207  // GetUint8 retrieves the value by specified <pattern> and converts it to uint8.
   208  func (j *Json) GetUint8(pattern string, def ...interface{}) uint8 {
   209  	return gconv.Uint8(j.Get(pattern, def...))
   210  }
   211  
   212  // GetUint16 retrieves the value by specified <pattern> and converts it to uint16.
   213  func (j *Json) GetUint16(pattern string, def ...interface{}) uint16 {
   214  	return gconv.Uint16(j.Get(pattern, def...))
   215  }
   216  
   217  // GetUint32 retrieves the value by specified <pattern> and converts it to uint32.
   218  func (j *Json) GetUint32(pattern string, def ...interface{}) uint32 {
   219  	return gconv.Uint32(j.Get(pattern, def...))
   220  }
   221  
   222  // GetUint64 retrieves the value by specified <pattern> and converts it to uint64.
   223  func (j *Json) GetUint64(pattern string, def ...interface{}) uint64 {
   224  	return gconv.Uint64(j.Get(pattern, def...))
   225  }
   226  
   227  // GetFloat32 retrieves the value by specified <pattern> and converts it to float32.
   228  func (j *Json) GetFloat32(pattern string, def ...interface{}) float32 {
   229  	return gconv.Float32(j.Get(pattern, def...))
   230  }
   231  
   232  // GetFloat64 retrieves the value by specified <pattern> and converts it to float64.
   233  func (j *Json) GetFloat64(pattern string, def ...interface{}) float64 {
   234  	return gconv.Float64(j.Get(pattern, def...))
   235  }
   236  
   237  // GetFloats retrieves the value by specified <pattern> and converts it to []float64.
   238  func (j *Json) GetFloats(pattern string, def ...interface{}) []float64 {
   239  	return gconv.Floats(j.Get(pattern, def...))
   240  }
   241  
   242  // GetInts retrieves the value by specified <pattern> and converts it to []int.
   243  func (j *Json) GetInts(pattern string, def ...interface{}) []int {
   244  	return gconv.Ints(j.Get(pattern, def...))
   245  }
   246  
   247  // GetStrings retrieves the value by specified <pattern> and converts it to []string.
   248  func (j *Json) GetStrings(pattern string, def ...interface{}) []string {
   249  	return gconv.Strings(j.Get(pattern, def...))
   250  }
   251  
   252  // GetInterfaces is alias of GetArray.
   253  // See GetArray.
   254  func (j *Json) GetInterfaces(pattern string, def ...interface{}) []interface{} {
   255  	return gconv.Interfaces(j.Get(pattern, def...))
   256  }
   257  
   258  // GetTime retrieves the value by specified <pattern> and converts it to time.Time.
   259  func (j *Json) GetTime(pattern string, format ...string) time.Time {
   260  	return gconv.Time(j.Get(pattern), format...)
   261  }
   262  
   263  // GetDuration retrieves the value by specified <pattern> and converts it to time.Duration.
   264  func (j *Json) GetDuration(pattern string, def ...interface{}) time.Duration {
   265  	return gconv.Duration(j.Get(pattern, def...))
   266  }
   267  
   268  // GetGTime retrieves the value by specified <pattern> and converts it to *gtime.Time.
   269  func (j *Json) GetGTime(pattern string, format ...string) *gtime.Time {
   270  	return gconv.GTime(j.Get(pattern), format...)
   271  }
   272  
   273  // Set sets value with specified <pattern>.
   274  // It supports hierarchical data access by char separator, which is '.' in default.
   275  func (j *Json) Set(pattern string, value interface{}) error {
   276  	return j.setValue(pattern, value, false)
   277  }
   278  
   279  // Remove deletes value with specified <pattern>.
   280  // It supports hierarchical data access by char separator, which is '.' in default.
   281  func (j *Json) Remove(pattern string) error {
   282  	return j.setValue(pattern, nil, true)
   283  }
   284  
   285  // Contains checks whether the value by specified <pattern> exist.
   286  func (j *Json) Contains(pattern string) bool {
   287  	return j.Get(pattern) != nil
   288  }
   289  
   290  // Len returns the length/size of the value by specified <pattern>.
   291  // The target value by <pattern> should be type of slice or map.
   292  // It returns -1 if the target value is not found, or its type is invalid.
   293  func (j *Json) Len(pattern string) int {
   294  	p := j.getPointerByPattern(pattern)
   295  	if p != nil {
   296  		switch (*p).(type) {
   297  		case map[string]interface{}:
   298  			return len((*p).(map[string]interface{}))
   299  		case []interface{}:
   300  			return len((*p).([]interface{}))
   301  		default:
   302  			return -1
   303  		}
   304  	}
   305  	return -1
   306  }
   307  
   308  // Append appends value to the value by specified <pattern>.
   309  // The target value by <pattern> should be type of slice.
   310  func (j *Json) Append(pattern string, value interface{}) error {
   311  	p := j.getPointerByPattern(pattern)
   312  	if p == nil {
   313  		return j.Set(fmt.Sprintf("%s.0", pattern), value)
   314  	}
   315  	switch (*p).(type) {
   316  	case []interface{}:
   317  		return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]interface{}))), value)
   318  	}
   319  	return fmt.Errorf("invalid variable type of %s", pattern)
   320  }
   321  
   322  // GetStruct retrieves the value by specified <pattern> and converts it to specified object
   323  // <pointer>. The <pointer> should be the pointer to an object.
   324  func (j *Json) GetStruct(pattern string, pointer interface{}, mapping ...map[string]string) error {
   325  	return gconv.Struct(j.Get(pattern), pointer, mapping...)
   326  }
   327  
   328  // GetStructs converts any slice to given struct slice.
   329  func (j *Json) GetStructs(pattern string, pointer interface{}, mapping ...map[string]string) error {
   330  	return gconv.Structs(j.Get(pattern), pointer, mapping...)
   331  }
   332  
   333  // GetScan automatically calls Struct or Structs function according to the type of parameter
   334  // <pointer> to implement the converting..
   335  func (j *Json) GetScan(pattern string, pointer interface{}, mapping ...map[string]string) error {
   336  	return gconv.Scan(j.Get(pattern), pointer, mapping...)
   337  }
   338  
   339  // GetScanDeep automatically calls StructDeep or StructsDeep function according to the type of
   340  // parameter <pointer> to implement the converting..
   341  func (j *Json) GetScanDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
   342  	return gconv.ScanDeep(j.Get(pattern), pointer, mapping...)
   343  }
   344  
   345  // GetMapToMap retrieves the value by specified <pattern> and converts it to specified map variable.
   346  // See gconv.MapToMap.
   347  func (j *Json) GetMapToMap(pattern string, pointer interface{}, mapping ...map[string]string) error {
   348  	return gconv.MapToMap(j.Get(pattern), pointer, mapping...)
   349  }
   350  
   351  // GetMapToMaps retrieves the value by specified <pattern> and converts it to specified map slice
   352  // variable.
   353  // See gconv.MapToMaps.
   354  func (j *Json) GetMapToMaps(pattern string, pointer interface{}, mapping ...map[string]string) error {
   355  	return gconv.MapToMaps(j.Get(pattern), pointer, mapping...)
   356  }
   357  
   358  // GetMapToMapsDeep retrieves the value by specified <pattern> and converts it to specified map slice
   359  // variable recursively.
   360  // See gconv.MapToMapsDeep.
   361  func (j *Json) GetMapToMapsDeep(pattern string, pointer interface{}, mapping ...map[string]string) error {
   362  	return gconv.MapToMapsDeep(j.Get(pattern), pointer, mapping...)
   363  }
   364  
   365  // Map converts current Json object to map[string]interface{}.
   366  // It returns nil if fails.
   367  func (j *Json) Map() map[string]interface{} {
   368  	j.mu.RLock()
   369  	defer j.mu.RUnlock()
   370  	return gconv.Map(*(j.p))
   371  }
   372  
   373  // Array converts current Json object to []interface{}.
   374  // It returns nil if fails.
   375  func (j *Json) Array() []interface{} {
   376  	j.mu.RLock()
   377  	defer j.mu.RUnlock()
   378  	return gconv.Interfaces(*(j.p))
   379  }
   380  
   381  // Struct converts current Json object to specified object.
   382  // The <pointer> should be a pointer type of *struct.
   383  func (j *Json) Struct(pointer interface{}, mapping ...map[string]string) error {
   384  	j.mu.RLock()
   385  	defer j.mu.RUnlock()
   386  	return gconv.Struct(*(j.p), pointer, mapping...)
   387  }
   388  
   389  // Structs converts current Json object to specified object slice.
   390  // The <pointer> should be a pointer type of []struct/*struct.
   391  func (j *Json) Structs(pointer interface{}, mapping ...map[string]string) error {
   392  	j.mu.RLock()
   393  	defer j.mu.RUnlock()
   394  	return gconv.Structs(*(j.p), pointer, mapping...)
   395  }
   396  
   397  // Scan automatically calls Struct or Structs function according to the type of parameter
   398  // <pointer> to implement the converting..
   399  func (j *Json) Scan(pointer interface{}, mapping ...map[string]string) error {
   400  	return gconv.Scan(*(j.p), pointer, mapping...)
   401  }
   402  
   403  // MapToMap converts current Json object to specified map variable.
   404  // The parameter of <pointer> should be type of *map.
   405  func (j *Json) MapToMap(pointer interface{}, mapping ...map[string]string) error {
   406  	j.mu.RLock()
   407  	defer j.mu.RUnlock()
   408  	return gconv.MapToMap(*(j.p), pointer, mapping...)
   409  }
   410  
   411  // MapToMaps converts current Json object to specified map variable slice.
   412  // The parameter of <pointer> should be type of []map/*map.
   413  func (j *Json) MapToMaps(pointer interface{}, mapping ...map[string]string) error {
   414  	j.mu.RLock()
   415  	defer j.mu.RUnlock()
   416  	return gconv.MapToMaps(*(j.p), pointer, mapping...)
   417  }
   418  
   419  // Dump prints current Json object with more manually readable.
   420  func (j *Json) Dump() {
   421  	j.mu.RLock()
   422  	defer j.mu.RUnlock()
   423  	gutil.Dump(*j.p)
   424  }
   425  
   426  // Export returns <j> as a string with more manually readable.
   427  func (j *Json) Export() string {
   428  	j.mu.RLock()
   429  	defer j.mu.RUnlock()
   430  	return gutil.Export(*j.p)
   431  }