Skip to content

Commit dd5f008

Browse files
authored
fix: Validate json strings and handle empty strings (#497)
Continuation of the work here https://github.com/cloudquery/plugin-sdk/pull/479/files
1 parent 7154bd0 commit dd5f008

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

schema/json.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,17 +51,45 @@ func (dst *JSON) Set(src interface{}) error {
5151

5252
switch value := src.(type) {
5353
case string:
54+
if value == "" {
55+
*dst = JSON{Bytes: []byte(""), Status: Null}
56+
return nil
57+
}
58+
// validate this is a valid json string
59+
err := json.Unmarshal([]byte(value), &struct{}{})
60+
if err != nil {
61+
return err
62+
}
5463
*dst = JSON{Bytes: []byte(value), Status: Present}
5564
case *string:
5665
if value == nil {
5766
*dst = JSON{Status: Null}
5867
} else {
68+
if *value == "" {
69+
*dst = JSON{Bytes: []byte(""), Status: Null}
70+
return nil
71+
}
72+
// validate this is a valid json
73+
err := json.Unmarshal([]byte(*value), &struct{}{})
74+
if err != nil {
75+
return err
76+
}
5977
*dst = JSON{Bytes: []byte(*value), Status: Present}
6078
}
6179
case []byte:
6280
if value == nil {
6381
*dst = JSON{Status: Null}
6482
} else {
83+
if string(value) == "" {
84+
*dst = JSON{Bytes: []byte(""), Status: Null}
85+
return nil
86+
}
87+
88+
// validate this is a valid json
89+
err := json.Unmarshal(value, &struct{}{})
90+
if err != nil {
91+
return err
92+
}
6593
*dst = JSON{Bytes: value, Status: Present}
6694
}
6795

schema/json_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ func TestJSONSet(t *testing.T) {
1313
source interface{}
1414
result JSON
1515
}{
16+
{source: "", result: JSON{Bytes: []byte(""), Status: Null}},
1617
{source: "{}", result: JSON{Bytes: []byte("{}"), Status: Present}},
1718
{source: []byte("{}"), result: JSON{Bytes: []byte("{}"), Status: Present}},
1819
{source: ([]byte)(nil), result: JSON{Status: Null}},

0 commit comments

Comments
 (0)