I am generating a JSON string from a PHP array to echo a JS object.
This is what I want to get in js:
var myVar = 123;
//php output:
var obj = {a:1, b:[1,2], c: myVar, d:Date.UTC(2014, 0, 07)}
This is what I have:
<?php
$array = array('a'=>1, 'b'=>array(1,2), 'c'=>???, 'd'=>???);
echo json_encode($array);
?>
The question is: What I put in PHP instead of question marks so that it won't be converted to string?
2 Answers 2
JSON doesn't support variables or special Date objects. You can only use scalar values (strings, numbers, booleans), arrays and objects (associative arrays).
A way to get what you want would be to return a .js file and have the browser execute that (by including it as a script) instead of transferring simple JSON data. Otherwise you could only define "special" strings that are handled by the receiving side. (For example, array ["var", "myVar"] could be parsed accordingly.)
1 Comment
You could actually do something like that:
<?php
$array = array('a'=>1, 'b'=>array(1,2),
'c'=>'@#myVar#@',
'd'=>'@#Date.UTC(2014, 0, 07)#@'
);
$json = json_encode($array);
echo preg_replace('/\"\@\#(.*?)\#\@\"/', '${1}', $json);
?>
But in js JSON.parse won't work, so:
eval("var x = " + json_from_php);
Not such a good idea, but if you need it, it'll work. Just remember not to use this with any "json" which are generated not by your server.
json_encodeit will always be parsed as a string I think.jsoon_encode(). Have a look at json.org definition for values. You could just code your own encoder, but that would not be according to the standard.