-
Notifications
You must be signed in to change notification settings - Fork 54
/
util.go
61 lines (55 loc) · 1.39 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package kazaam
import (
"encoding/json"
"github.com/qntfy/jsonparser"
)
// by default, kazaam does not fully validate input data. Use IsJson()
// if you need to confirm input is valid before transforming.
// Note: This operation is very slow and memory/alloc intensive
// relative to most transforms.
func IsJson(s []byte) bool {
var js map[string]interface{}
return json.Unmarshal(s, &js) == nil
}
// experimental fast validation with jsonparser
func IsJsonFast(s []byte) bool {
for _, c := range s {
switch c {
case ' ', '\n', '\r', '\t':
continue
case '{':
return isJsonInternal(s, jsonparser.Object)
case '[':
return isJsonInternal(s, jsonparser.Array)
default:
return false
}
}
return false
}
func isJsonInternal(s []byte, t jsonparser.ValueType) bool {
valid := true
if t == jsonparser.Array {
_, err := jsonparser.ArrayEach(s, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
if valid {
valid = isJsonInternal(value, dataType)
}
})
if err != nil || !valid {
return false
}
} else if t == jsonparser.Object {
err := jsonparser.ObjectEach(s, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
if valid {
valid = isJsonInternal(value, dataType)
}
return nil
})
if err != nil || !valid {
return false
}
} else if t == jsonparser.Unknown {
return false
}
return valid
}