note 90646 modified in function.json-decode by danbrown

From: Date: Sat, 02 May 2009 14:50:47 +0000
Subject: note 90646 modified in function.json-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154136@lists.php.net to get a copy of this message
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. --was-- 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 = 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. http://php.net/manual/en/function.json-decode.php

« previous php.notes (#154136) next »