Handling escaped slashes in a JSON string

I am trying to get json database and the code is as follows

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

So far I am converting a json object, and it looks like this.

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

I just applied \ to print the special character / , but it does not work. I applied a lot of things to print a special character. Is this a problem in converting a special character to JSON?

+1
source share
2 answers

As others have already mentioned, a 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 interpolating strings). However, if you read JSON, you could be forgiven for thinking it is (although you should always have RTM ;-)).

The reason you think you need to avoid the slash is due to the subtle difference in how PHP and Javascript interpolate the extra slashes. Consider the following line declaration, valid in both PHP and Javascript:

 "AC\/DC" 

In PHP, an extra backslash is treated as a literal, therefore:

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

In Javascript, the extra backslash is discarded, so:

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

JSON makes it possible to flush the slash, but json_encode() will take care of this acceleration for you. You do not need to add a backslash to a string. And due to the differences in the way these extra backslashes are interpolated, you cannot just take the JSON string and transfer it to your PHP source, because it will be interpreted as a different value.

Starting with PHP 5.4.0, you can set the JSON_UNESCAPED_SLASHES flag in json_encode() in PHP to prevent it from adding backslashes. However, this is optional and may result in a strict JSON parser rejecting the data.

So, to summarize, 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 should probably also include http:// at the beginning of the line and pass $row['file_name'] via urlencode() , since the data looks like a URL:

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

There is no need to avoid a slash, since it is not considered a special symbol.

You may need to replace / with //, since some systems break a single slash, when it is parsed / displayed, windows come to mind.

0
source

Source: https://habr.com/ru/post/948548/


All Articles