Home  >  Article  >  php教程  >  PHP处理JSON字符串key缺少双引号的解决方法,jsonkey

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

WBOY
WBOYOriginal
2016-06-13 09:25:201064browse

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

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

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

例如:

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

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

<&#63;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
&#63;>

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

<&#63;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" }
&#63;>

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

json值中含双引号,怎处理

用Replace吧"\""替换成""
 

助解析JSON对象时正则表达式的写法,对双引号的处理

废话不多说
直接上代码
json不会
js代码
a = '"越南查禁中国邮票 称所印西沙群岛为"越南领土""';var b;b = a.replace(/"越南领土"/,'\\"越南领土\\"');document.write(b);
 

Statement:
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