-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate-json.js
48 lines (43 loc) · 1.57 KB
/
validate-json.js
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
angular.module('jsondiff').
service('JsonValidatorService', function() {
var jvs = this;
jvs.isJSON = function(obj) {
// check "obj" for string
if (typeof obj === "string") {
// obj is string, parse it using JSON.parse()
try {
var isJSON = JSON.parse(obj);
// this is for null, as "null" is a valid JSON and type of null is object
// but "null" is itself falsey
// if isJSON is null then if( isJSON && ... ) will be false
if (isJSON && typeof isJSON === "object") {
// everything goes fine, return true
return true;
}
return false;
} catch (e) {
// cannot parse, invalid JSON
return false;
}
}
// "obj" is not string, so first,
// JSON.stringify() it, then parse
var jsonString = JSON.stringify(obj);
// now parse this json string
try {
var checkJSON = JSON.parse(jsonString);
// this is for null, as "null" is a valid JSON and type of null is object
// but "null" is itself falsey
// if isJSON is null then if( isJSON && ... ) will be false
if (checkJSON && typeof checkJSON === "object") {
// everything goes fine, return true
return true;
}
return false;
} catch (e) {
// cannot parse, invalid JSON
return false;
}
};
return jvs;
})