TehBucket TehBucket - 5 months ago 11
JSON Question

JSON encoded Multidimensional array returns wrong syntax (Unexpected ])

I have an array of arrays in PHP that I need to send to javascript as JSON. The PHP script and AJAX call work, but the returned JSON string is not parse-able JSON; instead of an array of arrays, it just sticks the arrays together with no separators or container.

Example JSON String:

[{"id":"77","options":[],"price":"4.25","title":"Zeppoli's","spec":""}][{"id":"78","options":[],"price":"7.95","title":"Battered Mushrooms","spec":""}]


PHP Snippet that creates above JSON String:

$cartArr = array(); // array of objects to be jsonified
foreach($products as $product){
unset($newItem);
$newItem = array(
"id" => $product['itemID'],
"options" => $theseOptions,
"price" => $product['price'],
"title" => $product['name'],
"spec" => $product["special"],
"cartid" => $product['ID']
);
array_push($cartArr,$newItem);
echo json_encode($cartArr);
}


An attempt to JSON.parse() the string will result in the following error, unless the string is manually corrected.

Uncaught SyntaxError: Unexpected token [

Answer

You're building json in a loop, which means you're outputting MULTIPLE independent json strings, which is illegal syntax. e.g. you're doing

[0,1,2][3,4,5]

which is two separate arrays jammed up against each other. It would have to be more like

[[0,1,2],[3,4,5]]

to be valid JSON. You encode to json LAST, after you've completely build your PHP data structure, not piecemeal in the middle of the construction process.

e.g.

foreach(...) {
   $array[] = more data ...
}
echo json_encode($array);
Comments