note 90646 deleted from function.json-decode by danbrown

From: Date: Sun, 10 May 2009 21:43:59 +0000
Subject: note 90646 deleted from function.json-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154429@lists.php.net to get a copy of this message
Note Submitter: Gravis ---- two regex statements will convert your string from javascript toSource() output format to JSON accepted format while preserving types. this works with sub objects too! <?php $str = '({strvar:"string", number:40, boolvar:true, subobject:{substrvar:"sub string", subsubobj:{deep:"deeply nested"}, strnum:"56"}, false_val:false, false_str:"false"})'; $str = substr($str, 1, strlen($str) - 2); $str = preg_replace("/([a-zA-Z0-9_]+?):/" , "\"$1\":", $str); // fix left side $str = preg_replace("/:(^false^true[a-zA-Z_]+[a-zA-Z0-9_]*)/", ":\"$1\"", $str); // fix right side $output = json_decode($str, true); var_dump($output); ?> var_dump output: array(6) { ["strvar"]=> string(6) "string" ["number"]=> int(40) ["boolvar"]=> bool(true) ["subobject"]=> array(3) { ["substrvar"]=> string(10) "sub string" ["subsubobj"]=> array(1) { ["deep"]=> string(13) "deeply nested" } ["strnum"]=> string(2) "56" } ["false_val"]=> bool(false) ["false_str"]=> string(5) "false" } you can see the types are properly preserved. hope this saves someone some time.

« previous php.notes (#154429) next »