in serialize/unserialize, replace toNumber argument with isJSON argument

This commit is contained in:
rolux 2013-02-18 11:38:31 +05:30
parent c718b0b8ef
commit 290d97cbee

View file

@ -149,16 +149,22 @@ Ox.methods = function(object, includePrototype) {
/*@ /*@
Ox.serialize <f> Parses an object into query parameters Ox.serialize <f> Parses an object into query parameters
> Ox.serialize({a: 1, b: 2, c: 3}) > Ox.serialize({a: 1, b: 2.3, c: -4})
'a=1&b=2&c=3' 'a=1&b=2.3&c=-4'
> Ox.serialize({a: -1, b: 2.3, c: [4, 5]}) > Ox.serialize({a: [], n: null, o: {}, s: '', u: void 0})
'a=-1&b=2.3&c=4,5' ''
> Ox.serialize({string: 'foo', empty: {}, null: null, undefined: void 0}) > Ox.serialize({a: [1, 2], b: true, n: 1, o: {k: 'v'}, s: 'foo'}, true)
'string=foo' 'a=[1,2]&b=true&n=1&o={"k":"v"}&s="foo"'
@*/ @*/
Ox.serialize = function(object) { Ox.serialize = function(object, isJSON) {
var ret = []; var ret = [];
Ox.forEach(object, function(value, key) { Ox.forEach(object, function(value, key) {
var value;
if (isJSON) {
try {
value = JSON.stringify(value);
} catch(e) {}
}
if (!Ox.isEmpty(value) && !Ox.isNull(value) && !Ox.isUndefined(value)) { if (!Ox.isEmpty(value) && !Ox.isNull(value) && !Ox.isUndefined(value)) {
ret.push(key + '=' + value); ret.push(key + '=' + value);
} }
@ -168,23 +174,28 @@ Ox.serialize = function(object) {
/*@ /*@
Ox.unserialize <f> Parses query parameters into an object Ox.unserialize <f> Parses query parameters into an object
> Ox.unserialize('a=1&b=2&c=3') > Ox.unserialize('a=1&b=2.3&c=-4')
{a: '1', b: '2', c: '3'} {a: '1', b: '2.3', c: '-4'}
> Ox.unserialize('a=-1&b=2.3&c=4,5', true) > Ox.unserialize('a=foo&b=&c&a=bar')
{a: -1, b: 2.3, c: [4, 5]} {a: 'bar'}
> Ox.unserialize('a=1&b=&c&a=0', true) > Ox.unserialize('a=[1,2]&b=true&n=1&o={"k":"v"}&s1="foo"&s2=bar', true)
{a: 0} {a: [1, 2], b: true, n: 1, o: {k: 'v'}, s1: 'foo', s2: 'bar'}
@*/ @*/
Ox.unserialize = function(string, toNumber) { Ox.unserialize = function(string, isJSON) {
var ret = {}; var ret = {};
Ox.filter(string.split('&')).forEach(function(value) { Ox.filter(string.split('&')).forEach(function(value) {
var array = value.split('='); var array = value.split('=');
if (array[1]) { if (array[1]) {
ret[array[0]] = !toNumber ? array[1] if (isJSON) {
: array[1].indexOf(',') == -1 ? +array[1] try {
: array[1].split(',').map(function(value) { ret[array[0]] = JSON.parse(array[1]);
return +value; } catch(e) {
}); ret[array[0]] = array[1];
}
} else {
ret[array[0]] = array[1];
}
} }
}); });
return ret; return ret;