note 95782 deleted from function.json-decode by salathe
| From: | salathe@php.net | Date: | Mon, 21 Sep 2020 15:01:36 +0000 |
| Subject: | note 95782 deleted from function.json-decode by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215436@lists.php.net to get a copy of this message | ||
Note Submitter: colin.mollenhour.com
----
For those of you wanting json_decode to be a little more lenient (more like Javascript), here is a
wrapper:
<?php
function json_decode_nice($json, $assoc = FALSE){
$json = str_replace(array("\n","\r"),"",$json);
$json =
preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json);
return json_decode($json,$assoc);
}
?>
Some examples of accepted syntax:
<?php
$json = '{a:{b:"c",d:["e","f",0]}}';
$json =
'{
a : {
b : "c",
"d.e.f": "g"
}
}';
?>
If your content needs to have newlines, do this:
<?php
$string = "This
Text
Has
Newlines";
$json = '{withnewlines:'.json_encode($string).'}';
?>
Note: This does not fix trailing commas or single quotes.
[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (sskaje AT gmail DOT com) on
05-DEC-2012 with the following note.]
Old regexp failed when json like
{aaa:[{a:1},{a:2}]}