3

I have a problem with the json functionality in zend and js.

I try to encode a single array containing some number of models like this:

echo json_encode(Application_Model_Marker::getMarkers());

var mark = JSON.parse(jsonVal); //in js

where getMarkers is a static method that returns an array of marker models.

This works fine and when I parse it in the js script and try accessing the values of the json object it works fine.

If however I try to create and send an array of array like this:

$allData = array();
$allData['info'] = Application_Model_Marker::getMarkers();
$allData['openingHours'] = Application_Model_Openinghours::getOpeningHours();
$allData['happyHours'] = Application_Model_Happyhour::getHappyHours();

echo json_encode($allData);

It still sends all the correct information when I try to alert(jsonVal.responseText); in js.

It has three arrays each containg some arrays of objects.

However when I try to initialize a variable to the parsed json object like in the first example, I can't access the values and it seems some kind of error occurs as the program stops when I try it.

I don't quite get it as it has all the correct info when i just try to print the response text from the encoded json object.

Any ideas how to do this multidimensional json encoding?

4
  • Can you clarify that »some kind of error«? Most of the time errors do help in pinpointing the cause and simply omitting it (or saying »it doesn't work«) makes the task very hard for others to help you. Commented Jul 21, 2012 at 23:24
  • How do you receive response and initialize jsonVal? The 1st parameter to JSON.parse() should be string variable, but you mentioned alert(jsonVal.responseText), so I guess jsonVal is an object? Then you may try JSON.parse(jsonVal.responseText) or jsonVal is already json-parsed object? Commented Jul 22, 2012 at 0:23
  • When debugging calls such as this, Firebug comes in handy. It allows you to debug your javascript/dom with errors and such. Secondly, have you tried accessing mark.info? Is it undefined? Commented Jul 22, 2012 at 3:32
  • mark.info is exactly undefined. I tried JSON.parse(jsonVal.responseText) which works with a single array as well but still not with several arrays. Commented Jul 23, 2012 at 8:47

1 Answer 1

0

Try this, Hopefully it'll work :

<sctript>
var mark;
eval("mark = "+jsonVal+";");
</sctrip>
2
  • I thought of trying eval but I've read that it's very bad practice compared to parse ? Commented Jul 23, 2012 at 8:48
  • if the data is yours From your server and you have full control over it, then eval isn't a bad practice . Commented Jul 25, 2012 at 12:41

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.