简体   繁体   中英

Cannot parse JSON returned from PHP

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!

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"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM