github.com/Ali-iotechsys/sqlboiler/v4@v4.0.0-20221208124957-6aec9a5f1f71/types/json.go (about) 1 package types 2 3 import ( 4 "database/sql/driver" 5 "encoding/json" 6 "errors" 7 8 "github.com/volatiletech/randomize" 9 ) 10 11 // JSON is an alias for json.RawMessage, which is 12 // a []byte underneath. 13 // JSON implements Marshal and Unmarshal. 14 type JSON json.RawMessage 15 16 // String output your JSON. 17 func (j JSON) String() string { 18 return string(j) 19 } 20 21 // Unmarshal your JSON variable into dest. 22 func (j JSON) Unmarshal(dest interface{}) error { 23 return json.Unmarshal(j, dest) 24 } 25 26 // Marshal obj into your JSON variable. 27 func (j *JSON) Marshal(obj interface{}) error { 28 res, err := json.Marshal(obj) 29 if err != nil { 30 return err 31 } 32 33 *j = res 34 return nil 35 } 36 37 // UnmarshalJSON sets *j to a copy of data. 38 func (j *JSON) UnmarshalJSON(data []byte) error { 39 if j == nil { 40 return errors.New("json: unmarshal json on nil pointer to json") 41 } 42 43 *j = append((*j)[0:0], data...) 44 return nil 45 } 46 47 // MarshalJSON returns j as the JSON encoding of j. 48 func (j JSON) MarshalJSON() ([]byte, error) { 49 return j, nil 50 } 51 52 // Value returns j as a value. 53 // Unmarshal into RawMessage for validation. 54 func (j JSON) Value() (driver.Value, error) { 55 var r json.RawMessage 56 if err := j.Unmarshal(&r); err != nil { 57 return nil, err 58 } 59 60 return []byte(r), nil 61 } 62 63 // Scan stores the src in *j. 64 func (j *JSON) Scan(src interface{}) error { 65 switch source := src.(type) { 66 case string: 67 *j = append((*j)[0:0], source...) 68 return nil 69 case []byte: 70 *j = append((*j)[0:0], source...) 71 return nil 72 default: 73 return errors.New("incompatible type for json") 74 } 75 } 76 77 // Randomize for sqlboiler 78 func (j *JSON) Randomize(nextInt func() int64, fieldType string, shouldBeNull bool) { 79 *j = []byte(`"` + randomize.Str(nextInt, 1) + `"`) 80 }