1

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 [
2
  • Your JSON is malformed. Each item is an object in its own array, when I believe you only want one array with multiple items. Commented Jun 15, 2016 at 16:36
  • 2
    Put your echo json_encode line outside of the loop. If there are multiple iterations, you end up with invalid JSON from having one after the other. e.g. [][] is invalid JSON. Commented Jun 15, 2016 at 16:36

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.