Skip to content

Commit

Permalink
✨ feat: jsonutil - add new util func IsJSON(), IsJSONFast() for check…
Browse files Browse the repository at this point in the history
… JSON
  • Loading branch information
inhere committed May 25, 2023
1 parent 0f1bbc1 commit d1fb1c8
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
29 changes: 29 additions & 0 deletions jsonutil/jsonutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,35 @@ func Mapping(src, dst any) error {
return Decode(bts, dst)
}

// IsJSON check if the string is valid JSON. (Note: uses json.Unmarshal)
func IsJSON(s string) bool {
if s == "" {
return false
}

var js json.RawMessage
return json.Unmarshal([]byte(s), &js) == nil
}

// IsJSONFast simple and fast check input string is valid JSON.
func IsJSONFast(s string) bool {
ln := len(s)
if ln < 2 {
return false
}
if ln == 2 {
return s == "{}" || s == "[]"
}

// object
if s[0] == '{' {
return s[ln-1] == '}' && s[1] == '"'
}

// array
return s[0] == '[' && s[ln-1] == ']'
}

// `(?s:` enable match multi line
var jsonMLComments = regexp.MustCompile(`(?s:/\*.*?\*/\s*)`)

Expand Down
26 changes: 26 additions & 0 deletions jsonutil/jsonutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,32 @@ func TestWriteReadFile(t *testing.T) {
assert.Eq(t, 200, user.Age)
}

func TestIsJsonFast(t *testing.T) {
testCases := []struct {
name string
input string
expected bool
}{
{"empty string", "", false},
{"single character", "a", false},
{"two characters object", "{}", true},
{"two characters slice", "[]", true},
{"invalid json", "{a}", false},
{"valid json object", `{"a": 1}`, true},
{"valid json array", `[1]`, true},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
assert.Eq(t, tc.expected, jsonutil.IsJSON(tc.input))

if jsonutil.IsJSONFast(tc.input) != tc.expected {
t.Errorf("expected %v but got %v", tc.expected, !tc.expected)
}
})
}
}

func TestStripComments(t *testing.T) {
is := assert.New(t)

Expand Down

0 comments on commit d1fb1c8

Please sign in to comment.