Skip to content

Commit 4242e5e

Browse files
authored
fix: Use json.Valid (#500)
So we support more types like arrays, strings, etc. ---
1 parent 9a9f46e commit 4242e5e

2 files changed

Lines changed: 13 additions & 12 deletions

File tree

schema/json.go

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"encoding/json"
66
"errors"
7+
"fmt"
78
"reflect"
89
)
910

@@ -55,10 +56,8 @@ func (dst *JSON) Set(src interface{}) error {
5556
*dst = JSON{Bytes: []byte(""), Status: Null}
5657
return nil
5758
}
58-
// validate this is a valid json string
59-
err := json.Unmarshal([]byte(value), &struct{}{})
60-
if err != nil {
61-
return err
59+
if !json.Valid([]byte(value)) {
60+
return fmt.Errorf("invalid json: %s", value)
6261
}
6362
*dst = JSON{Bytes: []byte(value), Status: Present}
6463
case *string:
@@ -69,10 +68,8 @@ func (dst *JSON) Set(src interface{}) error {
6968
*dst = JSON{Bytes: []byte(""), Status: Null}
7069
return nil
7170
}
72-
// validate this is a valid json
73-
err := json.Unmarshal([]byte(*value), &struct{}{})
74-
if err != nil {
75-
return err
71+
if !json.Valid([]byte(*value)) {
72+
return fmt.Errorf("invalid json: %s", *value)
7673
}
7774
*dst = JSON{Bytes: []byte(*value), Status: Present}
7875
}
@@ -85,10 +82,8 @@ func (dst *JSON) Set(src interface{}) error {
8582
return nil
8683
}
8784

88-
// validate this is a valid json
89-
err := json.Unmarshal(value, &struct{}{})
90-
if err != nil {
91-
return err
85+
if !json.Valid(value) {
86+
return fmt.Errorf("invalid json: %s", value)
9287
}
9388
*dst = JSON{Bytes: value, Status: Present}
9489
}

schema/json_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,13 @@ func TestJSONSet(t *testing.T) {
1515
}{
1616
{source: "", result: JSON{Bytes: []byte(""), Status: Null}},
1717
{source: "{}", result: JSON{Bytes: []byte("{}"), Status: Present}},
18+
{source: `"test"`, result: JSON{Bytes: []byte(`"test"`), Status: Present}},
19+
{source: "1", result: JSON{Bytes: []byte("1"), Status: Present}},
20+
{source: "[1, 2, 3]", result: JSON{Bytes: []byte("[1, 2, 3]"), Status: Present}},
1821
{source: []byte("{}"), result: JSON{Bytes: []byte("{}"), Status: Present}},
22+
{source: []byte(`"test"`), result: JSON{Bytes: []byte(`"test"`), Status: Present}},
23+
{source: []byte("1"), result: JSON{Bytes: []byte("1"), Status: Present}},
24+
{source: []byte("[1, 2, 3]"), result: JSON{Bytes: []byte("[1, 2, 3]"), Status: Present}},
1925
{source: ([]byte)(nil), result: JSON{Status: Null}},
2026
{source: (*string)(nil), result: JSON{Status: Null}},
2127

0 commit comments

Comments
 (0)