Skip to content

Instantly share code, notes, and snippets.

@incredimike
Last active July 15, 2017 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save incredimike/5375362 to your computer and use it in GitHub Desktop.
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
<?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"
}
*/
?>
@afayes
Copy link

afayes commented Nov 19, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment