-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathjson-stringify.js
More file actions
36 lines (25 loc) · 869 Bytes
/
Copy pathjson-stringify.js
File metadata and controls
36 lines (25 loc) · 869 Bytes
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
// Write a function that takes in an object and serializes it to JSON.
JSON = {}
JSON.stringify = JSON.stringify || function (obj) {
var stringified = '';
var type = typeof (obj);
if (type != "object" || obj === null) {
stringified += '"'+obj+'"';
return stringified
} else {
var json = [], isArr = (obj && obj.constructor == Array);
for (var key in obj) {
var value = obj[key],
t = typeof(value);
if (t == "string"){
value = '"' + value + '"';
} else if (t == "object" && value !== null){
value = JSON.stringify(value);
}
json.push((isArr ? "" : '"' + key + '":') + String(value));
}
return (isArr ? "[" : "{") + String(json) + (isArr ? "]" : "}");
}
};
cat = { 'hi': 2, 'secondkey': {'test': 2 }, 'third-key': [1,2,3] }
JSON.stringify(cat)