Created
October 14, 2016 21:52
-
-
Save jherax/a9bd7866005e14e56f01de0495c522be to your computer and use it in GitHub Desktop.
Converts a JavaScript value to a JSON string
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
// This is a reference to JSON.stringify and provides a polyfill for old browsers. | |
// stringify serializes an object, array or primitive value and return it as JSON. | |
var stringify = (function() { | |
var _PRIMITIVE, _OPEN, _CLOSE; | |
if (window.JSON && typeof JSON.stringify === "function") | |
return JSON.stringify; | |
_PRIMITIVE = /string|number|boolean|null/; | |
_OPEN = { | |
object: "{", | |
array: "[" | |
}; | |
_CLOSE = { | |
object: "}", | |
array: "]" | |
}; | |
//gets the type | |
function getType(value) { | |
if (value === null) return "null"; | |
if (value instanceof Array) return "array"; | |
return typeof value; | |
} | |
//actions to execute in each iteration | |
function action(key, value) { | |
var type = getType(value), | |
prop = ""; | |
//key is not an array index | |
if (typeof key !== "number") | |
prop = '"' + key + '":'; | |
if (type === "string") { | |
prop += '"' + value + '"'; | |
} else if (_PRIMITIVE.test(type)) { | |
prop += value; | |
} else if (type === "array" || type === "object") { | |
prop += toJson(value, type); | |
} else return; | |
this.push(prop); | |
} | |
//iterates over an object or array | |
function each(obj, callback, thisArg) { | |
for (var key in obj) { | |
if (obj instanceof Array) key = +key; | |
callback.call(thisArg, key, obj[key]); | |
} | |
} | |
//generates the json | |
function toJson(obj, type) { | |
var items = []; | |
each(obj, action, items); | |
return _OPEN[type] + items.join(",") + _CLOSE[type]; | |
} | |
//exported function that generates the json | |
return function stringify(obj) { | |
if (!arguments.length) return ""; | |
var type = getType(obj); | |
if (_PRIMITIVE.test(type)) | |
return (obj === null ? type : obj.toString()); | |
//obj is array or object | |
return toJson(obj, type); | |
} | |
}()); |
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
var myObject = { | |
"0": null, | |
"total-items": 10, | |
"undefined-prop": void(0), | |
sorted: true, | |
images: ["bg-menu.png", "bg-body.jpg", [1, 2]], | |
position: { //nested object literal | |
"x": 40, | |
"y": 300, | |
offset: [{ top: 23 }] | |
}, | |
onChange: function() { return !0 }, | |
pattern: /^bg-.+\.(?:png|jpe?g)$/i | |
}; | |
var json = stringify(myObject); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment