note 90790 modified in function.json-decode by danbrown

From: Date: Sun, 10 May 2009 21:43:41 +0000
Subject: note 90790 modified in function.json-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154428@lists.php.net to get a copy of this message
with two lines you can convert your string from JavaScript toSource() (see http://www.w3schools.com/jsref/jsref_toSource.asp) output format to JSON accepted format. this works with subobjects too! note: toSource() is part of JavaScript 1.3 but only implemented in Mozilla based javascript engines (not Opera/IE/Safari/Chrome). <?php $str = '({strvar:"string", number:40, boolvar:true, subobject:{substrvar:"sub string", subsubobj:{deep:"deeply nested"}, strnum:"56"}, false_val:false, false_str:"false"})'; // example javascript object toSource() output $str = substr($str, 1, strlen($str) - 2); // remove outer ( and ) $str = preg_replace("/([a-zA-Z0-9_]+?):/" , "\"$1\":", $str); // fix variable names $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" } hope this saves someone some time. --was-- i made the comment http://us.php.net/manual/en/function.json-decode.php#90646 and i have realized that the second regex never does anything so i removed it and i changed some text. therefore, i would like to replace it with the following: with two lines you can convert your string from JavaScript toSource() (see http://www.w3schools.com/jsref/jsref_toSource.asp) output format to JSON accepted format. this works with subobjects too! note: toSource() is part of JavaScript 1.3 but only implemented in Mozilla based javascript engines (not Opera/IE/Safari/Chrome). <?php $str = '({strvar:"string", number:40, boolvar:true, subobject:{substrvar:"sub string", subsubobj:{deep:"deeply nested"}, strnum:"56"}, false_val:false, false_str:"false"})'; // example javascript object toSource() output $str = substr($str, 1, strlen($str) - 2); // remove outer ( and ) $str = preg_replace("/([a-zA-Z0-9_]+?):/" , "\"$1\":", $str); // fix variable names $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" } hope this saves someone some time. http://php.net/manual/en/function.json-decode.php

« previous php.notes (#154428) next »