From 5bfc555b9ec31e034de5733d5a1ba1ebe0dd6b35 Mon Sep 17 00:00:00 2001 From: rolux Date: Sat, 26 May 2012 14:33:50 +0200 Subject: [PATCH] add Ox.fallback.JSON --- source/Ox/js/Fallback.js | 77 +++++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 8 deletions(-) diff --git a/source/Ox/js/Fallback.js b/source/Ox/js/Fallback.js index 639c11b6..2745208f 100644 --- a/source/Ox/js/Fallback.js +++ b/source/Ox/js/Fallback.js @@ -136,6 +136,66 @@ Ox.fallback.isArray = function(value) { return Object.prototype.toString.call(value) == '[object Array]'; }; +/*@ +Ox.fallback.JSON see https://github.com/douglascrockford/JSON-js + > Ox.fallback.JSON.parse('{"a": [1, 2], "b": [3, 4]}') + {a: [1, 2], b: [3, 4]} + > Ox.fallback.JSON.stringify([(function(){ return arguments; }()), false, null, 0, Infinity, NaN, / /, void 0]) + '[{},false,null,0,null,null,{},null]' +@*/ +Ox.fallback.JSON = (function() { + var replace = { + '"': '\\"', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\\': '\\\\' + }; + function quote(value) { + return '"' + value.split('').map(function(char) { + return replace[char] || char; + }).join('') + '"'; + }; + return { + parse: function parse(string) { + try { + return eval('(' + string + ')'); + } catch (e) { + throw new SyntaxError(); + } + }, + stringify: function stringify(value) { + var ret = 'null', type = Ox.typeOf(value); + if (type == 'arguments' || type == 'regexp') { + ret = '{}'; + } else if (type == 'array') { + ret = ['[', ']'].join( + value.map(function(v) { + return stringify(v); + }).join(',') + ); + } else if (type == 'boolean') { + ret = String(value); + } else if (type == 'date') { + ret = Ox.getISODate(value); + } else if (type == 'number') { + ret = isFinite(value) ? String(value) : 'null'; + } else if (type == 'object') { + ret = ['{', '}'].join( + value.map(function(v, k) { + return quote(k) + ': ' + stringify(v); + }).join(',') + ); + } else if (type == 'string') { + ret = quote(value) + } + return ret; + } + }; +}()); + /*@ Ox.fallback.keys see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys > Ox.fallback.keys({a: 1, b: 2, c: 3}) @@ -275,15 +335,16 @@ Ox.fallback.trim = function() { }; (function(global) { - var log, method, object; - for (method in Ox.fallback) { - object = method == 'bind' ? Function.prototype - : method == 'isArray' ? Array - : method == 'keys' ? Object - : method == 'trim' ? String.prototype + var key, log, object; + for (key in Ox.fallback) { + object = key == 'bind' ? Function.prototype + : key == 'isArray' ? Array + : key == 'JSON' ? global + : key == 'keys' ? Object + : key == 'trim' ? String.prototype : Array.prototype; - if (!object[method]) { - object[method] = Ox.fallback[method]; + if (!object[key]) { + object[key] = Ox.fallback[key]; } } // In IE8, window.console.log is an object,