In PHP, converting an array into JSON format can be achieved through the json_encode
function. This function accepts a parameter $value
and converts it into a JSON format string. However, by default, the json_encode
function will wrap the object's attribute name in double quotes when generating a JSON string, which will affect the use of some front-end frameworks. So, how to make the json_encode
function remove the double quotes in the generated JSON string?
First, let’s take a look at the JSON string format generated by the json_encode
function by default:
$arr = array('name' => '张三', 'age' => 18, 'gender' => 'male'); $jsonStr = json_encode($arr); echo $jsonStr;
The output result of the above code is:
{"name":"张三","age":18,"gender":"male"}
Yes As you can see, the attribute names in the JSON string are all wrapped in double quotes.
If we want to remove the double quotes, we can use PHP's reflection mechanism. If the reader is not familiar with reflection, you can learn about it after reading this article.
The following is an example of removing double quotes from attribute names in a JSON string:
class JsonWithoutQuotes { public function __construct($data) { $this->originalData = $data; } public function getJson() { $data = $this->originalData; $jsonData = json_encode($data); $jsonData = preg_replace_callback( '/"(.*?)":/is', function($matches) { $match = $matches[1]; return is_string($match) ? $match.":" : $match; }, $jsonData); return $jsonData; } }
In the above code, we use a custom classJsonWithoutQuotes
, which receives an array as parameter and saves it in the $originalData
property. The getJson
method is used to convert the array in $originalData
into a JSON string without double quotes:
First, we call json_encode
The function converts the original data into a JSON string, and then uses PHP's built-in regular expression engine preg_replace_callback
method to replace the attribute name in the JSON string with the string returned in the callback function. The function of the callback function is to determine whether a matched string is of string type. If so, return the string without double quotes. If not, return the string as is.
$arr = array('name' => '张三', 'age' => 18, 'gender' => 'male'); $jsonStr = (new JsonWithoutQuotes($arr))->getJson(); echo $jsonStr;
Actual running effect:
{name:"张三",age:18,gender:"male"}
You can see that the double quotes have been removed from the attribute names in the JSON string.
Summary:
It is very convenient to use the json_encode
function that comes with PHP to convert an array into a JSON string. However, in some cases, property names in JSON strings need to be stripped of double quotes. At this time, we can use the PHP reflection mechanism to achieve this goal.
The above is the detailed content of How to convert php array to json and remove double quotes. For more information, please follow other related articles on the PHP Chinese website!