PHP solves the problem of JSON string key missing double quotation marks

Source: Internet
Author: User
Tags learn php programming
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.