0

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!

1
  • for(var i in json) console.log(json[i]); Commented May 22, 2013 at 7:34

3 Answers 3

4

Try this

var json = 'yourjsonstring',//'{"key1":"value1","key2":"value2"}'
var obj = JSON.parse(json);
alert(obj.key1);
1
  • Jep, thats the solution. Thanks! Commented May 22, 2013 at 7:35
0

Try this code

function parseJSON(jsonString){
  return eval("(" + jsonString + ")");
}

var object = parseJson(StringFromPhp);

You can get mykey like:

object.key1  // value1
0

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!

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.