Rutger Huijsmans
Rutger Huijsmans

Reputation: 2408

Return JSON using PHP

Currently I'm returning a message from my PHP backend like so:

$data = [ 'message' => 'Number doesn\'t exist!'];
$this->set_response(json_encode($data), REST_Controller::HTTP_CREATED);

This will create a message looking like this:

"{\"message\":\"Number doesn't exist!\"}"

I however am hoping to get a message looking like this:

{
    "message": "Number doesn't exist!"
}

What am I doing wrong?

Upvotes: 1

Views: 97

Answers (3)

devpro
devpro

Reputation: 16117

You can use JSON_UNESCAPED_SLASHES as second parameter in json_encode().

$data = [ 'message' => 'Number doesn\'t exist!'];
$encoded = json_encode($data,JSON_UNESCAPED_SLASHES);
$this->set_response($encoded, REST_Controller::HTTP_CREATED);

Other Solution:

$data = [ 'message' => 'Number doesn\'t exist!'];
$string = $this->set_response(json_encode($data), REST_Controller::HTTP_CREATED); // your current result
$decode = json_decode($string,true); // decode the value 
echo json_encode($decode,JSON_UNESCAPED_SLASHES); //and use JSON_UNESCAPED_SLASHES in json_encode()

Upvotes: 3

Rax Weber
Rax Weber

Reputation: 3780

You must decode the JSON response.

json_decode($your_response);

Upvotes: 0

Narendra Sharma
Narendra Sharma

Reputation: 29

brother you just need to call your json as json_encode($data,true) and decode it like this json_decode($data,true); Happy Coding if the above doesn't seem to work second try

The \ is to escape the quotes (") that are part of the response.

Use stripslashes() to strip these out.

When a string wrapped in quotes contains quotes, they have to be escaped. The escape character in php is \

Upvotes: 0

Related Questions