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