PHP处理JSON字符串key缺少双引号的解决方法

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP处理JSON字符串key缺少引号的解决方法,分享给大家供大家参考之用。具体方法如下:

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

例如:

<?php
$data = array('name'=>'fdipzone');
echo json_encode($data);            // {"name":"fdipzone"}
print_r(json_decode(json_encode($data), true)); //Array ( [name] => fdipzone )
?>

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

<?php
$str = '{"name":"fdipzone"}';
var_dump(json_decode($str, true)); // array(1) { ["name"]=> string(8) "fdipzone" }

$str1 = '{name:"fdipzone"}';
var_dump(json_decode($str1, true)); // NULL
?>

解决方法:判断是否存在缺少双引括起来的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('/\w:/', $str)){
    $str = preg_replace('/(\w+):/is', '"$1":', $str);
  }
  return json_decode($str, $mode);
}

$str = '{"name":"fdipzone"}';
var_dump(ext_json_decode($str, true)); // array(1) { ["name"]=> string(8) "fdipzone" }

$str1 = '{name:"fdipzone"}';
var_dump(ext_json_decode($str1, true)); // array(1) { ["name"]=> string(8) "fdipzone" }
?>

希望本文所述对大家PHP程序设计的学习有所帮助。

相关文章

基于flush()不能按顺序输出时的解决办法

如果是在linux下, 首先确认是否添加 ob_start() 和 ob_flush().复制代码 代码如下:ob_start();for ($i=1; $i<=10; $i++)...

解析php二分法查找数组是否包含某一元素

二分法查找数组是否包含某一元素,兼容正反序,代码实现:复制代码 代码如下:<?php $searchValue = (int)$_GET['key']; fun...

php单元测试phpunit入门实例教程

本文实例讲述了php单元测试phpunit。分享给大家供大家参考,具体如下: 这篇文章提供了一些phpunit官方教程没有提到的信息,帮助初学者快速了解php单元测试,在phpunit官...

提高define性能的php扩展hidef的安装和使用

提高define性能的php扩展hidef的安装和使用

官网:http://pecl.php.net/package/hidef简介:  Allow definition of user defined constants in simple...

php获取百度收录、百度热词及百度快照的方法

本文实例讲述了php获取百度收录、百度热词及百度快照的方法。分享给大家供大家参考。具体如下: 获取百度收录: <?php /* 抓取百度收录代码 */ function...