Handling escaped slashes in a JSON string

2019-08-04 23:40发布

问题:

I'm trying to get the json of the database and the code goes like this

   $path["file_name"] = "www.119.com\/assets\/demo\/large\/".$row["file_name"];

While I convert to a json object and it shows like this.

www.119.com\\\/assets\\\/demo\\\/large\\\/demo1.png

I just applied \ to print special character /, but it's not working. I applied many things to print the special character. Is it a problem in converting special character to JSON?

回答1:

As has been mentioned by others, a forward slash is not a special character inside a string, in PHP or in Javascript (and since JSON is derived from Javascript it follows the same rules for string interpolation). However if you were reading some JSON, you could be forgiven for thinking that it is (although you should always RTM ;-) ).

The reason you think you need to escape the slash is due to a subtle difference in the way PHP and Javascript interpolate superfluous forward slashes. Consider the following string declaration, valid in both PHP and Javascript:

"AC\/DC"

In PHP, the extra backslash is treated as a literal, so:

echo "AC\/DC"; // outputs AC\/DC

In Javascript, the extra backslash is dropped, so:

console.log("AC\/DC"); // logs AC/DC

JSON mandates the escaping of forward slashes, but json_encode() will take care of this escaping for you. You do not need to add the backslashes to the string yourself. And because of the difference in the way these additional backslashes are interpolated, you cannot simply take a JSON string and drop it into your PHP source - because it will will be interpretted as a different value.

Since PHP 5.4.0 you can supply the JSON_UNESCAPED_SLASHES flag to json_encode() in PHP to prevent it from adding the backslashes. However this is unnecessary and may cause a strict JSON parser to reject the data.

So to sum up, the correct way to declare your string in PHP is:

$path["file_name"] = "www.119.com/assets/demo/large/".$row["file_name"];

As a side note, you probably also what to include http:// at the beginning of the string and pass $row['file_name'] through urlencode() as well, since the data appears to be a URL:

$path["file_name"] = "http://www.119.com/assets/demo/large/".urlencode($row["file_name"]);


回答2:

There should be no need to escape the slash as its not considered a special character.

You might need to replace / with // as some systems strip a single slash when its being parsed/displayed, windows comes to mind.



标签: php json slash