Skip to content

Commit

Permalink
✨ feat: jsonutil - add new util func: IsArray, IsObject for quick che…
Browse files Browse the repository at this point in the history
…ck json string
  • Loading branch information
inhere committed Sep 8, 2023
1 parent b53b4e7 commit 5644d92
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
34 changes: 29 additions & 5 deletions jsonutil/jsonutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,15 @@ func Mapping(src, dst any) error {
return Decode(bts, dst)
}

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

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

// IsJSONFast simple and fast check input string is valid JSON.
// IsJSONFast simple and fast check input is valid JSON array or object.
func IsJSONFast(s string) bool {
ln := len(s)
if ln < 2 {
Expand All @@ -94,6 +92,32 @@ func IsJSONFast(s string) bool {
return s[0] == '[' && s[ln-1] == ']'
}

// IsArray check if the string is valid JSON array.
func IsArray(s string) bool {
ln := len(s)
if ln < 2 {
return false
}
return s[0] == '[' && s[ln-1] == ']'
}

// IsObject check if the string is valid JSON object.
func IsObject(s string) bool {
ln := len(s)
if ln < 2 {
return false
}
if ln == 2 {
return s == "{}"
}

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

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

Expand Down
17 changes: 17 additions & 0 deletions jsonutil/jsonutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,23 @@ func TestIsJsonFast(t *testing.T) {
}
})
}

// test IsArray
t.Run("IsArray", func(t *testing.T) {
assert.True(t, jsonutil.IsArray(`[]`))
assert.True(t, jsonutil.IsArray(`[1]`))
assert.False(t, jsonutil.IsArray(`{"a": 1}`))
assert.False(t, jsonutil.IsArray(`a`))
})

// test IsObject
t.Run("IsObject", func(t *testing.T) {
assert.True(t, jsonutil.IsObject(`{}`))
assert.True(t, jsonutil.IsObject(`{"a": 1}`))
assert.False(t, jsonutil.IsObject(`[1]`))
assert.False(t, jsonutil.IsObject(``))
assert.False(t, jsonutil.IsObject(`a`))
})
}

func TestStripComments(t *testing.T) {
Expand Down

0 comments on commit 5644d92

Please sign in to comment.