diff --git a/schema/json.go b/schema/json.go index 0ca3d01ee7..bd3d4b55a5 100644 --- a/schema/json.go +++ b/schema/json.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "reflect" ) @@ -55,10 +56,8 @@ func (dst *JSON) Set(src interface{}) error { *dst = JSON{Bytes: []byte(""), Status: Null} return nil } - // validate this is a valid json string - err := json.Unmarshal([]byte(value), &struct{}{}) - if err != nil { - return err + if !json.Valid([]byte(value)) { + return fmt.Errorf("invalid json: %s", value) } *dst = JSON{Bytes: []byte(value), Status: Present} case *string: @@ -69,10 +68,8 @@ func (dst *JSON) Set(src interface{}) error { *dst = JSON{Bytes: []byte(""), Status: Null} return nil } - // validate this is a valid json - err := json.Unmarshal([]byte(*value), &struct{}{}) - if err != nil { - return err + if !json.Valid([]byte(*value)) { + return fmt.Errorf("invalid json: %s", *value) } *dst = JSON{Bytes: []byte(*value), Status: Present} } @@ -85,10 +82,8 @@ func (dst *JSON) Set(src interface{}) error { return nil } - // validate this is a valid json - err := json.Unmarshal(value, &struct{}{}) - if err != nil { - return err + if !json.Valid(value) { + return fmt.Errorf("invalid json: %s", value) } *dst = JSON{Bytes: value, Status: Present} } diff --git a/schema/json_test.go b/schema/json_test.go index 084342c685..8847036848 100644 --- a/schema/json_test.go +++ b/schema/json_test.go @@ -15,7 +15,13 @@ func TestJSONSet(t *testing.T) { }{ {source: "", result: JSON{Bytes: []byte(""), Status: Null}}, {source: "{}", result: JSON{Bytes: []byte("{}"), Status: Present}}, + {source: `"test"`, result: JSON{Bytes: []byte(`"test"`), Status: Present}}, + {source: "1", result: JSON{Bytes: []byte("1"), Status: Present}}, + {source: "[1, 2, 3]", result: JSON{Bytes: []byte("[1, 2, 3]"), Status: Present}}, {source: []byte("{}"), result: JSON{Bytes: []byte("{}"), Status: Present}}, + {source: []byte(`"test"`), result: JSON{Bytes: []byte(`"test"`), Status: Present}}, + {source: []byte("1"), result: JSON{Bytes: []byte("1"), Status: Present}}, + {source: []byte("[1, 2, 3]"), result: JSON{Bytes: []byte("[1, 2, 3]"), Status: Present}}, {source: ([]byte)(nil), result: JSON{Status: Null}}, {source: (*string)(nil), result: JSON{Status: Null}},