//
$foo = array(
'number' => 1,
'float' => 1.5,
'array' => array(1,2),
'string' => 'bar' ,
'function' => 'function(){return "foo bar";}'
);
// JSON
$json = json_encode($foo);
//
echo $json;
* This source code was highlighted with Source Code Highlighter .
{
"number" :1,
"float" :1.5,
"array" :[1,2],
"string" : "bar" ,
"function" : "function(){return \"foo bar\";}"
}
* This source code was highlighted with Source Code Highlighter .
// .
$foo = array(
'number' => 1,
'float' => 1.5,
'array' => array(1,2),
'string' => 'bar' ,
'function' => 'function(){return "foo bar";}'
);
$value_arr = array();
$replace_keys = array();
foreach ($foo as $key => &$ value ){
//
if (strpos($ value , 'function(' )===0){
// .
$value_arr[] = $ value ;
// '' ..
$ value = '%' . $key . '%' ;
// .
$replace_keys[] = '"' . $ value . '"' ;
}
}
// JSON
$json = json_encode($foo);
// $json :
{
"number" :1,
"float" :1.5,
"array" :[1,2],
"string" : "bar" ,
"function" : "%function%"
}
// .
$json = str_replace($replace_keys, $value_arr, $json);
// .
echo $json;
// JSON :
{
"number" :1,
"float" :1.5,
"array" :[1,2],
"string" : "bar" ,
"function" :function(){ return "foo bar" ;}
}
* This source code was highlighted with Source Code Highlighter .
Now, in the resulting object, “function” is not a string, but a function. Actually the problem is solved. If you use this solution with Prototype, it will look something like this:new Ajax.Request( 'json_server.php' , {
method: 'get' ,
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
alert(json.function()); // => alert 'foo bar'
}
});
* This source code was highlighted with Source Code Highlighter .
$foo = array(
'integer' =>9,
'string' => 'test string' ,
'function' => Zend_Json_Expr(
'function(){ window.alert("javascript function encoded by Zend_Json") }'
),
);
Zend_Json::encode($foo, false , array( 'enableJsonExprFinder' => true ));
// it will returns json encoded string:
{
"integer" :9,
"string" : "test string" ,
"function" :function(){
window.alert( "javascript function encoded by Zend_Json" )
}
}
* This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/63057/
All Articles