1

Possible Duplicate:
How to parse JSON in JavaScript

I am pulling a multi-object associative array out of PHP. An example is below:

$displayArray[] = array("Name"=>"Joe", "Important"=>"1", "Group"=>"Family");
$displayArray[] = array("Name"=>"Jane", "Important"=>"0", "Group"=>"Family");
echo json_encode($displayArray);

Using AJAX, the returned JSON string is so:

[{"Name":"Joe","Important":"1","Group":"Family"},{"Name":"Jane","Important":"0","Group":"Family"}]

I would like to convert this JSON data into a Javascript array. Help appreciated.

Community
  • 1
  • 1
Jeremy
  • 883
  • 1
  • 20
  • 41

1 Answers1

2

Looks like you're using jQuery. The return from .ajax() isn't the object you're echo back to the browser via PHP. Instead, you can access the returned data using the success callback, e.g.:

var myData;

$.ajax({ type: 'POST', 
       url: 'ReadToggle.php', 
       dataType:'json', 
       async: false })
       success: function(data) {
                    myData = data;
       }
})

You can then parse myData like a standard javascript object, e.g.:

myData[index]

I think most people tend to write their code to handle the returned object in the success function itself, e.g.:

var myData;

$.ajax({ type: 'POST', 
       url: 'ReadToggle.php', 
       dataType:'json', 
       async: false })
       success: function(data) {
                    console.log(data);
                    console.log(data[0]);
       }
})
ernie
  • 6,356
  • 23
  • 28
  • Fantastic. Thanks Ernie. I looped so: for(var index in myData) { document.write( 'Name' + " : " + myData[index]['Name'] + "
    "); document.write( 'Important' + " : " + myData[index]['Important'] + "
    "); document.write( 'Group' + " : " + myData[index]['Group'] + "
    "); }
    – Jeremy Dec 14 '12 at 21:36
  • @Jeremy glad to help. Like I said, most people put that into the actually success function, rather than using a separate var and code external to the .ajax() call. – ernie Dec 14 '12 at 21:37