Last active
July 15, 2017 04:34
-
-
Save incredimike/5375362 to your computer and use it in GitHub Desktop.
I added a 3rd regex to the json_decode_nice function by "colin.mollenhour.com" to handle a trailing comma in json definition. Original function here: http://www.php.net/manual/en/function.json-decode.php#95782
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function json_decode_nice($json, $assoc = FALSE){ | |
$json = str_replace(array("\n","\r"),"",$json); | |
$json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json); | |
$json = preg_replace('/(,)\s*}$/','}',$json); | |
return json_decode($json,$assoc); | |
} | |
// Example: | |
$dat_json = <<<EOF | |
{ | |
"foo" : "bam", | |
"bar" : "baz", | |
} | |
EOF; | |
$dat_array = json_decode_nice( $dat_json ); | |
var_dump ( $dat_json, $dat_array ); | |
/* RESULTS: | |
string(35) "{ | |
"foo" : "bam", | |
"bar" : "baz", | |
}" | |
array(2) { | |
["foo"]=> | |
string(3) "bam" | |
["bar"]=> | |
string(3) "baz" | |
} | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesnt work for indexed based arrays e.g.
{
"a": [1,2,3,]
}
This regular expression from PHP website does: $json=preg_replace('/,\s*([]}])/m', '$1', $json);
but it doesnt handle this situation:
{
"a" : "a,b,c," // this is valid and not a trailing comma but it gets detected as a trailing comma
}
If someone could modify the above regular expression so that it does not remove trailing commas from string values that would be perfect