TehBucket TehBucket - 1 year ago 54
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){
$newItem = array(
"id" => $product['itemID'],
"options" => $theseOptions,
"price" => $product['price'],
"title" => $product['name'],
"spec" => $product["special"],
"cartid" => $product['ID']
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 [


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


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


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.


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