Skip to content

Commit 27160f2

Browse files
committed
Merge remote-tracking branch 'pakohan/master' into NullJSONText
2 parents 5f97679 + c52770c commit 27160f2

File tree

2 files changed

+42
-6
lines changed

2 files changed

+42
-6
lines changed

types/types.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,14 @@ func (g *GzippedText) Scan(src interface{}) error {
5757
// implements `Unmarshal`, which unmarshals the json within to an interface{}
5858
type JSONText json.RawMessage
5959

60-
// MarshalJSON returns j as the JSON encoding of j.
61-
func (j JSONText) MarshalJSON() ([]byte, error) {
62-
return j, nil
60+
var _EMPTY_JSON = JSONText("{}")
61+
62+
// MarshalJSON returns the *j as the JSON encoding of j.
63+
func (j *JSONText) MarshalJSON() ([]byte, error) {
64+
if len(*j) == 0 {
65+
*j = _EMPTY_JSON
66+
}
67+
return *j, nil
6368
}
6469

6570
// UnmarshalJSON sets *j to a copy of data
@@ -86,11 +91,17 @@ func (j JSONText) Value() (driver.Value, error) {
8691
// Scan stores the src in *j. No validation is done.
8792
func (j *JSONText) Scan(src interface{}) error {
8893
var source []byte
89-
switch src.(type) {
94+
switch t := src.(type) {
9095
case string:
91-
source = []byte(src.(string))
96+
source = []byte(t)
9297
case []byte:
93-
source = src.([]byte)
98+
if len(t) == 0 {
99+
source = _EMPTY_JSON
100+
} else {
101+
source = t
102+
}
103+
case nil:
104+
*j = _EMPTY_JSON
94105
default:
95106
return errors.New("Incompatible type for JSONText")
96107
}
@@ -100,6 +111,9 @@ func (j *JSONText) Scan(src interface{}) error {
100111

101112
// Unmarshal unmarshal's the json in j to v, as in json.Unmarshal.
102113
func (j *JSONText) Unmarshal(v interface{}) error {
114+
if len(*j) == 0 {
115+
*j = _EMPTY_JSON
116+
}
103117
return json.Unmarshal([]byte(*j), v)
104118
}
105119

types/types_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,28 @@ func TestJSONText(t *testing.T) {
3939
if err == nil {
4040
t.Errorf("Was expecting invalid json to fail!")
4141
}
42+
43+
j = JSONText("")
44+
v, err = j.Value()
45+
if err != nil {
46+
t.Errorf("Was not expecting an error")
47+
}
48+
49+
err = (&j).Scan(v)
50+
if err != nil {
51+
t.Errorf("Was not expecting an error")
52+
}
53+
54+
j = JSONText(nil)
55+
v, err = j.Value()
56+
if err != nil {
57+
t.Errorf("Was not expecting an error")
58+
}
59+
60+
err = (&j).Scan(v)
61+
if err != nil {
62+
t.Errorf("Was not expecting an error")
63+
}
4264
}
4365

4466
func TestBitBool(t *testing.T) {

0 commit comments

Comments
 (0)