1

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?

4
  • 1
    $data = [ 'message' => 'Number doesn\'t exist!']; echo json_encode($data); expected result return. check your this function set_response Commented Sep 30, 2016 at 6:16
  • Yes problem in set_response @devpro Commented Sep 30, 2016 at 6:22
  • 1
    yes agreed, maybe JSON_UNESCAPED_SLASHES will resolve @HaRsH Commented Sep 30, 2016 at 6:22
  • i hope u got the solution now. Commented Sep 30, 2016 at 6:53

3 Answers 3

3

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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 \

2 Comments

expected result required in json. not in array
json_encode() has only one parameter. decode has 2 parameter
0

You must decode the JSON response.

json_decode($your_response);

Comments

Your Answer

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.