Created
October 6, 2013 14:05
-
-
Save mmis1000/6854516 to your computer and use it in GitHub Desktop.
a light toJSONString() implement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object.prototype.toJSONString = function () { | |
var i, x, content, returnValue; | |
if (this instanceof Array) { | |
for (i = 0; i < this.length; i++) { | |
if (this[i] !== undefined) { | |
if (this[i] != null) { | |
content = content ? (content + "," + this[i].toJSONString()) : this[i].toJSONString(); | |
} else { | |
content = content ? (content + "," + "null") : "null"; | |
} | |
} else { | |
content = content ? (content + "," + "undefined") : "undefined"; | |
} | |
} | |
returnValue = "[" + content + "]"; | |
} else { | |
for (x in this) { | |
if (this.hasOwnProperty(x)) { | |
if (this[x] !== undefined) { | |
if (this[x] != null) { | |
content = content ? (content + "," + x + ":" + this[x].toJSONString()) : (x + ":" + this[x].toJSONString()); | |
} else { | |
content = content ? (content + "," + x + ":" + "null") : (x + ":" + "null"); | |
} | |
} else { | |
content = content ? (content + "," + x + ":" + "undefined") : (x + ":" + "undefined"); | |
} | |
} | |
} | |
returnValue = "{" + content + "}"; | |
} | |
return returnValue; | |
}; | |
Boolean.prototype.toJSONString = function () { | |
return this.toString(); | |
}; | |
Number.prototype.toJSONString = function () { | |
return this.toString(); | |
}; | |
String.prototype.toJSONString = function () { | |
var temp; | |
temp = this.toString(); | |
temp = temp.replace(/(\\|\")/g, "\\$1"); | |
temp = temp.replace("\n", "\\n"); | |
temp = temp.replace("\r", "\\r"); | |
temp = temp.replace("\f", "\\f"); | |
temp = temp.replace("\r", "\\r"); | |
return "\"" + temp + "\""; | |
}; | |
Function.prototype.toJSONString = function () { | |
return this.toString(); | |
}; | |
RegExp.prototype.toJSONString = function () { | |
return this.toString(); | |
}; | |
Math.toJSONString = function () { | |
return "Math"; | |
}; | |
Date.prototype.toJSONString = function () { | |
return "new Date(" + this.getTime() + ")"; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment