Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove backslash on json_encode() function?

How to remove the (\)backslash on a string? when using echo json_encode() ?

For example:

<?php $str = "$(\"#output\").append(\"<p>This is a test!</p>\")";  echo json_encode($str); ?> 

note: When you echo $str, there will be no problem... but when you echo out using json_encode(), the (\)backslash will show up.

Is there a way to solve this?

like image 677
Ryan Avatar asked Sep 02 '11 11:09

Ryan


People also ask

How do I get rid of extra slashes in JSON?

Replace slash everywhere in the string----------->str =str. replace(/\//g,""); You can convert back to JSON object again using-->var output =JSON. parse(str);

Why does my JSON string have backslash?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.

What is Json_encode function?

The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Syntax : string json_encode( $value, $option, $depth ) Parameters: $value: It is a mandatory parameter which defines the value to be encoded.


2 Answers

json_encode($response, JSON_UNESCAPED_SLASHES); 
like image 144
Rijk Avatar answered Sep 20 '22 15:09

Rijk


Since PHP 5.4 there are constants which can be used by json_encode() to format the json reponse how you want.

To remove backslashes use: JSON_UNESCAPED_SLASHES. Like so:

json_encode($response, JSON_UNESCAPED_SLASHES); 

View the PHP documentation for more constants and further information:

http://php.net/manual/en/function.json-encode.php

List of JSON constants:

http://php.net/manual/en/json.constants.php

like image 28
Daveloper87 Avatar answered Sep 22 '22 15:09

Daveloper87