github.com/kunlun-qilian/sqlx/v3@v3.0.0/datatypes/json_scanner.go (about)

     1  package datatypes
     2  
     3  import (
     4  	"database/sql/driver"
     5  	"fmt"
     6  
     7  	"github.com/kunlun-qilian/utils/json"
     8  )
     9  
    10  func JSONScan(dbValue interface{}, value interface{}) error {
    11  	switch v := dbValue.(type) {
    12  	case []byte:
    13  		bytes := v
    14  		if len(bytes) > 0 {
    15  			return json.Unmarshal(bytes, value)
    16  		}
    17  		return nil
    18  	case string:
    19  		str := v
    20  		if str == "" {
    21  			return nil
    22  		}
    23  		return json.Unmarshal([]byte(str), value)
    24  	case nil:
    25  		return nil
    26  	default:
    27  		return fmt.Errorf("cannot sql.Scan() from: %#v", value)
    28  	}
    29  }
    30  
    31  func JSONValue(value interface{}) (driver.Value, error) {
    32  	if zeroCheck, ok := value.(interface {
    33  		IsZero() bool
    34  	}); ok {
    35  		if zeroCheck.IsZero() {
    36  			return "", nil
    37  		}
    38  	}
    39  	bytes, err := json.Marshal(value)
    40  	if err != nil {
    41  		return "", err
    42  	}
    43  	str := string(bytes)
    44  	if str == "null" {
    45  		return "", nil
    46  	}
    47  	return str, nil
    48  }