Reputation: 7233
I have a PHP array, like that:
$myArray = array('key1' => value1, 'key2' => value2);
I am converting it to JSON using this code:
$js = json_encode($myArray);
Now in my JavaScript code I want to access the JS array (object?) by its keys, key1 for example, but it doesnt work, the result is always undefined.
Thanks!
Upvotes: 0
Views: 51
Reputation: 1104
First, you parse the JSON. There are different options to do that, but for example:
var parsedData = JSON.parse(your_data);
And then you access to the key you're looking for. The following is an "associative" way to access to an array (check this out).
alert (parsedData.your_key);
Good luck!
Upvotes: 0
Reputation: 781
Try this code
function parseJSON(jsonString){
return eval("(" + jsonString + ")");
}
var object = parseJson(StringFromPhp);
You can get mykey like:
object.key1 // value1
Upvotes: 0
Reputation: 11830
Try this
var json = 'yourjsonstring',//'{"key1":"value1","key2":"value2"}'
var obj = JSON.parse(json);
alert(obj.key1);
Upvotes: 4