0

In PHP, I have an Array of JSON Strings I need to return to JavaScript via an AJAX call. If I only have one element in the Array, I am able to call JSON.parse() on the response.

Ex (PHP):

$data = [];
array_push($data, '{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}');
echo json_encode($data);

Ex (JavaScript):

data = JSON.parse(data);

Yields the following, which I can further process and display:

["{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}"]

However, if I push two Elements to the Array:

$data = [];
array_push($data, '{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}');
array_push($data, '{"Date" : "12/12/2015", "Number" : "456", "Status" : "Processing"}');
echo json_encode($data);

I get the following in the Response:

["{"Date" : "11/11/2015", "Number" : "123", "Status" : "Order Received"}", 
 "{"Date" : "12/12/2015", "Number" : "456", "Status" : "Processing"}"]

When I try and JSON.parse() that, I'm blowing up on the double-quotes around the comma separating the two Elements.

}", "{

I've tried to address this in the PHP by encoding/decoding the Array/String(s) before sending the Response back, but had no luck. I also tried to address this in the JS by calling JSON.stringify() to try and reformat the Response, but no luck there either.

Wondering if anyone know the proper encode/decode/parse/stringify pattern to use.

Thanks for any input on this!

asked Nov 29, 2015 at 17:51
1
  • 1
    Shouldn't be an issue, json_encode should produce valid JSON, unless you're echoing and parsing more than once etc. Commented Nov 29, 2015 at 17:54

1 Answer 1

4

You have to populate array correctly before converting to JSON with PHP

$data = array();
$data = [];
array_push($data, 
 array( "Date" => "11/11/2015", 
 "Number" => "123", 
 "Status" => "Order Received"
 ));
echo json_encode($data);

This will give you following output:

[{"Date":"11\/11\/2015","Number":"123","Status":"Order Received"}]
Dan Cornilescu
39.8k12 gold badges61 silver badges102 bronze badges
answered Nov 29, 2015 at 17:55

2 Comments

Ah, I see, I need to push a new Array as each Array Element, not a String. Thanks much!
Exactly. The function "json_encode" translates a normal PHP array into JSON object. You can use an associative array to create more complex structures. WBR

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.