This article mainly introduces how PHP handles JSON string keys without double quotation marks, which is a very common type of error handling situation, for more information about how to handle JSON string keys in PHP, see the example below. The specific method is as follows:
Generally, the JSON string is a string in the form of key: value, and the normal key is enclosed by 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, if the key of the json string lacks Double quotation, json_decode will fail.
<?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: determine whether there is a missing double-cited key. if the key is missing, replace the regular expression with "key" and perform the json_decode operation.
<? Php/** JSON String parsing without double quotation of compatible Keys * @ 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 will help you learn PHP programming.