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