user1856596
user1856596

Reputation: 7233

PHP Array as JavaScript - accessing the JavaScript elements by key?

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

Answers (3)

Hector Ordonez
Hector Ordonez

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

Jeff Lee
Jeff Lee

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

chandresh_cool
chandresh_cool

Reputation: 11830

Try this

var json = 'yourjsonstring',//'{"key1":"value1","key2":"value2"}'
var obj = JSON.parse(json);
alert(obj.key1);

Upvotes: 4

Related Questions