note 95782 modified in function.json-decode by danbrown

From: Date: Thu, 06 Dec 2012 14:05:38 +0000
Subject: note 95782 modified in function.json-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192291@lists.php.net to get a copy of this message
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}]} --was-- 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. http://php.net/manual/en/function.json-decode.php

« previous php.notes (#192291) next »