note 90790 deleted from function.json-decode by salathe
| From: | salathe@php.net | Date: | Mon, 21 Sep 2020 15:01:14 +0000 |
| Subject: | note 90790 deleted from function.json-decode by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215434@lists.php.net to get a copy of this message | ||
Note Submitter: Gravis
----
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.