Explanation on the solution to the problem of missing double quotes in JSON string key

jacklove
Release: 2023-03-31 08:24:01
Original
3705 people have browsed it

JSON字符串key缺少引号的解决方法

JSON字符串是key:value形式的字符串,正常key是由双引号括起来的

例如:

<?php
$data = array(&#39;name&#39;=>&#39;fdipzone&#39;);
echo json_encode($data);                        // {"name":"fdipzone"}
print_r(json_decode(json_encode($data), true)); //Array ( [name] => fdipzone )
?>
Copy after login

但如果json字符串的key缺少双引括起来,则json_decode会失败。

<?php
$str = &#39;{"name":"fdipzone"}&#39;;
var_dump(json_decode($str, true)); // array(1) { ["name"]=> string(8) "fdipzone" }
$str1 = &#39;{name:"fdipzone"}&#39;;
var_dump(json_decode($str1, true)); // NULL
?>
Copy after login

解决方法:判断是否存在缺少双引括起来的key,如缺少则先用正则替换为"key",再进行json_decode操作。

<?php
/** 兼容key没有双引括起来的JSON字符串解析
* @param  String  $str JSON字符串
* @param  boolean $mod true:Array,false:Object
* @return Array/Object
*/
function ext_json_decode($str, $mode=false){
    if(preg_match(&#39;/\w:/&#39;, $str)){
        $str = preg_replace(&#39;/(\w+):/is&#39;, &#39;"$1":&#39;, $str);
    }
    return json_decode($str, $mode);
}
$str = &#39;{"name":"fdipzone"}&#39;;
var_dump(ext_json_decode($str, true)); // array(1) { ["name"]=> string(8) "fdipzone" }
$str1 = &#39;{name:"fdipzone"}&#39;;
var_dump(ext_json_decode($str1, true)); // array(1) { ["name"]=> string(8) "fdipzone" }
?>
Copy after login

本文讲解了关于JSON字符串key缺少双引号的解决方法 的讲解,更多相关内容请关注php中文网。

相关推荐:

关于mysql 严格模式 Strict Mode的说明讲解

php使用explode分割字符串新手容易忽略的问题的讲解

关于mysql互换表中两列数据方法的讲解


The above is the detailed content of Explanation on the solution to the problem of missing double quotes in JSON string key. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!