I'm doing some extensive testing to learn how PHP and JS variables, objects, arrays etc can be passed to one another successfully. There's a lot of confusing questions / answers on this subject.
As far as my testing has shown, I can create a variety of PHP objects:
$testarray = ["this", "is", "me"];
$testobject = (object) array("this"=>"that", "is"=>"was", "me"=>"him");
$teststring = "this is me";
$testnum = 9758.25;
and then I can pass them through json_encode()
(still in PHP)
echo '<script>
var testarray = '.json_encode($testarray).';
var testobject = '.json_encode($testobject).';
var teststring = '.json_encode($teststring).';
var testnum = '.json_encode($testnum).';
</script>';
and when run, this results in:
<script>
var testarray = ["this","is","me"];
var testobject = {"this":"that","is":"was","me":"him"};
var teststring = "this is me";
var testnum = 9758.25;
</script>
I just want to confirm that this result is, and always will be, perfectly valid JavaScript? I can't see anything wrong with it, yet some sources recommend the use of JSON.parse()
. Is this needed in this context?
I know that if an array or object in JS was passed through JSON.stringify()
, I'd have to parse it.
I also know that to send objects or arrays from JS to PHP, I'd have to use JSON.stringify()
and json_decode()
to make them valid, but it seems that json_encode()
results in valid JS without having to use JSON.parse()
?
Yes it is valid, because JSON syntax is a subset of JavaScript object literal syntax. Therefore if you inject JSON-encoded text into generated JS code in the way you've shown then it behaves as an object literal, just as if you'd written it there by hand.
JSON.parse
would be required if you were receiving a string containing JSON-encoded text into a JavaScript variable (e.g. as the result of an AJAX request) and needed to convert it from a string into a usable object.