Click here to Skip to main content
16,018,264 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am facing some issue with json object and json array in PHP response. When I am returning multiple records then response comes in "[ {...}, {...} ]" square bracket but if there is only 1 record then it returns json object "{...}" i.e not adding the square bracket.

I want to send a response in json array and not in json object.....

Please suggest
Posted
Comments
Zoltán Zörgő 1-Jul-13 16:15pm    
Share your php code where you generate the returned result.
Phionix11 1-Jul-13 16:19pm    
Here is my code, of JsonResponse file

class JsonResponse{
public $timestamp;
public $success;
public $message;
public $result;

function __construct($success, $errorMessage, $result){
$this->timestamp=gmdate('Y-m-d\TH:m:s\Z');
$this->success = $success;
$this->message = $errorMessage;
$this->result = $result;
}
}

and in another file i use this to send response result back,

echo json_encode(new JsonResponse($this->success, $this->message, $this->result));

here "$this->result" contains actual result from mysql
Zoltán Zörgő 1-Jul-13 16:45pm    
Ok, and how is that $result constructed? As you can fetch only one record at a time, that array is built by you. How exactly?
Phionix11 1-Jul-13 17:27pm    
Below is response result that I get,when there are multiple records then it shows json array,when there is only 1 record then it shows json object and if there is no record then it shows null.

Example 1]Response:-
{
"success":true,
"message":null,
"result":
{
"TravelData":
[
{ "travelMode":"Bus","Distance":"30" },
{ "travelMode":"Car","Distance":"22" },
{ "travelMode":"Cycling","Distance":"24" },

],

"HomeHeatingData":
[
{ "billType":"Electricity","amount":"650" },
{ "billType":"Phone","amount":"300" }
],
"FootPrintData":
{ "userId":"147",
"Saved":"12.76",
"Produced":"35084.55"
}
}
}

Example 2]
Response:-
{
"success":true,
"message":null,
"result":
[
{"date":"2013-05-24","Produced":"854.93","Saved":"0.02"},
{"date":"2013-05-25","Produced":"854.93","Saved":"0.28"},
{"date":"2013-05-28","Produced":"854.93","Saved":"0.17"},
{"date":"2013-05-30","Produced":"857.82","Saved":"3.45"},
{"date":"2013-05-31","Produced":"862.61","Saved":"0.00"}

]
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900