0

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.

2 Answers 2

1

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);
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

@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?
json_encode return a string, to have it treated as JSON in javascript it needs to be not a string.
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.
0

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).

1 Comment

It cannot throw arr not defined because the OP uses arr as the array variable and has already checked $.isArray(arr)==true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.