Skip to content

Instantly share code, notes, and snippets.

Last active July 15, 2017 04:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
I added a 3rd regex to the json_decode_nice function by "" to handle a trailing comma in json definition. Original function here:
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",
$dat_array = json_decode_nice( $dat_json );
var_dump ( $dat_json, $dat_array );
string(35) "{
"foo" : "bam",
"bar" : "baz",
array(2) {
string(3) "bam"
string(3) "baz"
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