Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode can not escape single quotation marks?

Tags:

json

php

$emailFields =  array(
    array(
        'name' => 'comments', 
        'type' => 'html', 
        'content' => "ahfsd\jfh/sf's askghaskg sadf"
    ),
);
echo json_encode($emailFields);

The print is

[{
    "name": "comments",
    "type": "html",
    "content": "ahfsd\\jfh/sf's askghaskg sadf"
}]

Why the json_encode can not escape the '?

like image 985
Frank Avatar asked Sep 05 '25 03:09

Frank


2 Answers

If you would like to convert any ` to \u0027 you can do it by using the following code:

json_encode($emailFields, JSON_HEX_APOS)

Or you can map your array and escape the apostrophe on each value. I'm not sure what you're trying to achieve and why you want to escape it, but I gave you some tools and you will decide by your self.

like image 194
MyLibary Avatar answered Sep 08 '25 00:09

MyLibary


As JSON Docs say, strings in JSON are surrounded by double quotes. There is no need to escape single quote in JSON.

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

Also

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string.

You should escape double quotes in your string values.

like image 22
btlm Avatar answered Sep 07 '25 23:09

btlm