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.

17
  • 1
    Your second code sample is as a JS array Commented Dec 14, 2012 at 21:08
  • 3
    You can use JSON.parse() to do so. Keep in mind that you may need to polyfill this for use in older browsers . Commented Dec 14, 2012 at 21:11
  • 3
    @Jeremy: Show us your AJAX code. You probably just need to add JSON.parse(). Commented Dec 14, 2012 at 21:15
  • 2
    @Jeremy, use JSON.parse() like m90 said. Commented Dec 14, 2012 at 21:16
  • 1
    @JonathanM: For JSON parsing??? Commented Dec 14, 2012 at 21:21

1 Answer 1

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

2 Comments

Fantastic. Thanks Ernie. I looped so: for(var index in myData) { document.write( 'Name' + " : " + myData[index]['Name'] + "<br />"); document.write( 'Important' + " : " + myData[index]['Important'] + "<br />"); document.write( 'Group' + " : " + myData[index]['Group'] + "<br />"); }
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.