Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slash issue with json_encode. Why and how to solve it?

Why outputting this date ("2011/7/11") with json_encode displays ("2011\/7\/11")?

How can I convert "2011\/7\/11" to "2011/7/11"?

$data_go = '2011/7/11';
$ddmmyyy='([1-9][\d]{3})[- \/.]([0-1][\d])[- \/.]([0-3][\d])';
            if(preg_match("/$ddmmyyy$/", $data_go)) {
            $year = substr($data_go,0,4);
            $month = substr($data_go,5,2);
            $day = substr($data_go,8,2);
            $j2g = $this->convert_date->JalaliToGregorian($year, $month, $day);
             $ok = $j2g[0]."/".$j2g[1]."/".$j2g[2];
            }else {
              return FALSE;
            }
echo json_encode($ok); // output "2011\/7\/11"
like image 375
Me hdi Avatar asked Jul 19 '11 07:07

Me hdi


People also ask

Why are there slashes in my JSON file?

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.

How remove slashes from JSON encode in PHP?

The stripslashes() function removes backslashes added by the addslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

What is the use of json_encode?

The json_encode() function is used to encode a value to JSON format.

What does json_encode return?

Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.


1 Answers

In PHP 5.4, you can use JSON_UNESCAPED_SLASHES:

echo json_encode("2011/7/11", JSON_UNESCAPED_SLASHES);

Otherwise, you have to do some trivial post-processing

str_replace('\\/', '/', json_encode("2011/7/11"));

Note that \/ is a valid way to represent / in JSON.

like image 142
Artefacto Avatar answered Oct 17 '22 08:10

Artefacto