github.com/gogf/gf@v1.16.9/encoding/gjson/gjson_stdlib_json_util.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  	"bytes"
    11  	"github.com/gogf/gf/internal/json"
    12  	"github.com/gogf/gf/util/gconv"
    13  )
    14  
    15  // Valid checks whether <data> is a valid JSON data type.
    16  // The parameter <data> specifies the json format data, which can be either
    17  // bytes or string type.
    18  func Valid(data interface{}) bool {
    19  	return json.Valid(gconv.Bytes(data))
    20  }
    21  
    22  // Encode encodes any golang variable <value> to JSON bytes.
    23  func Encode(value interface{}) ([]byte, error) {
    24  	return json.Marshal(value)
    25  }
    26  
    27  // Decode decodes json format <data> to golang variable.
    28  // The parameter <data> can be either bytes or string type.
    29  func Decode(data interface{}) (interface{}, error) {
    30  	var value interface{}
    31  	if err := DecodeTo(gconv.Bytes(data), &value); err != nil {
    32  		return nil, err
    33  	} else {
    34  		return value, nil
    35  	}
    36  }
    37  
    38  // Decode decodes json format <data> to specified golang variable <v>.
    39  // The parameter <data> can be either bytes or string type.
    40  // The parameter <v> should be a pointer type.
    41  func DecodeTo(data interface{}, v interface{}) error {
    42  	decoder := json.NewDecoder(bytes.NewReader(gconv.Bytes(data)))
    43  	// Do not use number, it converts float64 to json.Number type,
    44  	// which actually a string type. It causes converting issue for other data formats,
    45  	// for example: yaml.
    46  	//decoder.UseNumber()
    47  	return decoder.Decode(v)
    48  }
    49  
    50  // DecodeToJson codes json format <data> to a Json object.
    51  // The parameter <data> can be either bytes or string type.
    52  func DecodeToJson(data interface{}, safe ...bool) (*Json, error) {
    53  	if v, err := Decode(gconv.Bytes(data)); err != nil {
    54  		return nil, err
    55  	} else {
    56  		return New(v, safe...), nil
    57  	}
    58  }