0

I have a rest api created in php. Sharing a sample here:

public function getApiData(){
$returnData = ["a"=>"A","b"=>"B"];
header("Content-Type: application/json");
// I want to return the data in the json format for which i have two options.
// Option 1:
return $returnData
// Option 2 (if i don't use the option 1 to return):
#jsonResponse = json_encode($returnData,JSON_FORCE_OBJECT);
print_r($jsonResponse);
}

For the option 1 the response is JSON but its just a string for ex:

"{\"a\":\"A\",\"b\":\"B.\"}"

For the option 2 the response is JSON but it's appended with square opening and closing bracket. ex:

{
 "a":"A",
"b":"B"
}[]

Notice that there is an opening and closing bracket in the end. If i use die() or exit; after the print_r statement then those square brackets are remove. But the problem is that i don't want to use both of them.

Is there any option to send pure JSON object in the response of rest API?

Postman response with the option 1 Postman response with the option 1

1 Answer 1

0

Please do this

public function getApiData(){
$returnData = ["a"=>"A","b"=>"B"];

// Option 2 (if i don't use the option 1 to return):
$jsonResponse = json_encode($returnData,JSON_FORCE_OBJECT);
print_r($jsonResponse);

}
5
  • That is the problem, it returns incorrect json as explained by the output of option 2. It is appended by a [] square brackets.
    – Sudhir
    Commented Aug 4, 2020 at 14:25
  • Can you please check with $jsonResponse = json_encode($returnData); Commented Aug 4, 2020 at 14:33
  • I tried with that too. Not working.
    – Sudhir
    Commented Aug 4, 2020 at 16:18
  • @Sudhir have you got the solution?
    – usman
    Commented Nov 10, 2020 at 12:15
  • @usman sorry for the late reply. I didn't find any solution so had to do it the dirty way to remove ' [] ' from the end of the json on the consuming end. Since i had only one client as a consumer so i didn't had to look further.
    – Sudhir
    Commented Nov 26, 2020 at 7:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.