tags:

views:

421

answers:

2

Hi stackers,

I'm trying to take a jSON encoded string out of my database and loop through the items but I'm having some difficulty. Here's the string in the database:

["volunteers","seat_dedication_program","memberships"]

And here is the code:

//Looks for _checkbox when looping through my database fields (object dbVals) and turns it into a true jQuery array if it finds it.
if( key.search(/_checkbox/i) > 0 ) var arr = $.makeArray(dbVals[key]);

//If it is an array, loop through the array values and show them
if($.isArray(arr)==true){
    $.each(arr, function(i, n){
        alert(i + " : " + n);
    });
}

What I want is this:

//alert
0 : volunteers
//alert
1 : seat_dedication_program etc...

What I'm getting is this:

//alert
0 : ["volunteers","seat_dedication_program","memberships"]

I think I've included all relevant data. Can anyone help me figure out why this is happening?

Thanks.

A: 

Just use a regular for loop:

for (var i=0; i<arr.length; i++) {
    var n = arr[i];
    alert(i + " : " + n);
}

or for large arrays, the slightly optimized:

for (var i=0,l=arr.length; i<l; i++) {
    var n = arr[i];
    alert(i + " : " + n);
}

or if you really hate for loops:

Array.prototype.each = function (callback) {
    for (var index=0,l=this.length;index<l;index++) {
        var item = this[index];

        // index is second arg since it's optional
        callback(item,index);
    }
}

arr.each(function(n,i){
    alert(i + " : " + n);
});

but I'd recommend the for loop to avoid clashing with library modifications or when Firefox suddenly decide to implement its own each method for arrays (some libraries have already been bitten by this).

slebetman
This throws and error of "arr not defined"
jeerose
It cannot throw arr not defined because the OP uses `arr` as the array variable and has already checked `$.isArray(arr)==true`
slebetman
And yet, it is.
jeerose
Ahh. I see.. the error is the JSON string is not parsed.
slebetman
+1  A: 

Using $.makeArray(..) is giving you an array where the only element is the string you gave it. You need to parse the string into a JavaScript object. Use the JSON2.js library to parse then your code would look something like this.

var arr = JSON.parse(dbVals[key]);

if($.isArray(arr)==true){
    $.each(arr, function(i, n){
        alert(i + " : " + n);
    });
}
Carl
@Carl, that's what I thought (only element is the string I gave it) but when I use json_encode in php, why should I then have to parse it?
jeerose
json_encode return a string, to have it treated as JSON in javascript it needs to be not a string.
Greg
Like @Greg said, json_encode gives you a string (object -> string). In PHP, you'd use json_decode to get back to an object. Since you're in JS, JSON.parse(..) is the analog to json_decode.
Carl
Carl, you're amazing. Thank-you.
jeerose