PHP Processing JSON String key Lack of Double Quotation Marks

  • 2021-07-18 07:41:53
  • OfStack

This article describes the example of PHP processing JSON string key lack of quotation marks solution, to share for your reference. The specific methods are as follows:

Typically, JSON strings are strings in the form of key: value, and normal key is enclosed in double quotation marks.

For example:


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

However, json_decode fails if the key of the json string is missing a double reference.


<?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
?>

Solution: Judge whether there is a lack of key with double citations. If there is a lack, replace it with "key" with regularity first, and then perform json_decode operation.


<?php
/**  Compatible key There is no double citation JSON String parsing 
* @param String $str JSON String 
* @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" }
?>

I hope this article is helpful to everyone's study of PHP programming.


Related articles: