OK, so you're sending data to a client via AJAX and JSON. Now, you want to send a big multipli-nested array back up to the server. So, where's the json_encode for Javascript?
There isn't one. That's because the JSON notation was written for loading objects up in Javascript, not preparing them for AJAX. So this little chunk repairs that small but significant oversite. It uses reentrance to be fast and will handle normal indexed arrays and associative arrays. You simply say, var myStr = json_encode(theArr) and you're all set.
Enjoy!
/p
function json_encode(inVal) { return _json_encode(inVal).join(''); }
function _json_encode(inVal, out)
{
out = out || new Array();
var undef; // undefined
switch (typeof inVal)
{
case 'object':
if (!inVal)
{
out.push('null');
} else {
if (inVal.constructor == Array)
{
// Need to make a decision... if theres any associative elements of the array
// then I will block the whole thing as an object {} otherwise, I'll block it
// as a normal array []
var testVal = inVal.length;
var compVal = 0;
for (var key in inVal) compVal++;
if (testVal != compVal)
{
// Associative
out.push('{');
i = 0;
for (var key in inVal)
{
if (i++ > 0) out.push(',\n');
out.push('"');
out.push(key);
out.push('":');
_json_encode(inVal[key], out);
}
out.push('}');
} else {
// Standard array...
out.push('[');
for (var i = 0; i < inVal.length; ++i)
{
if (i > 0) out.push(',\n');
_json_encode(inVal[i], out);
}
out.push(']');
}
} else if (typeof inVal.toString != 'undefined') {
out.push('{');
var first = true;
for (var i in inVal)
{
var curr = out.length; // Record position to allow undo when arg[i] is undefined.
if (!first) out.push(',\n');
_json_encode(i, out);
out.push(':');
_json_encode(inVal[i], out);
if (out[out.length - 1] == undef)
{
out.splice(curr, out.length - curr);
} else {
first = false;
}
}
out.push('}');
}
}
return out;
case 'unknown':
case 'undefined':
case 'function':
out.push(undef);
return out;
case 'string':
out.push('"');
out.push(inVal.replace(/(["\\])/g, '\$1').replace(/\r/g, '').replace(/\n/g, '\n'));
out.push('"');
return out;
default:
out.push(String(inVal));
return out;
}
}