i have encoded my required data in the json object ,but i want to decode the json object into a javscript array, my json encoded object is :
{"product_id":"62","product_quantity":"65"}
however i want to use this json in my java script and want it to be available to a java script array
so if i do :
var arr = new Array()
arr = <?php json_decode('$json_object',TRUE); ?>;
however when i check my page source i get null i.e arr =
how can i assign my json object converted to array to java script array ?
further how to access the json objects from java script array ?
json_decodereturns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it throughjson_encode(and then actuallyechothe string that it returns).Note that
json_encodeoutputs a JavaScript data structure that is safe for injecting into a<script>element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren’t legal JSON on their own).Note that there is also no point in creating a new array and assigning it to
arrif you are going to immediately assign something else toarr.Also note that
'$json_object'will give you a string starting with the$character and then the name of the variable. Single quoted string in PHP are not interpolated.Also note that this JSON:
Will transform in to a PHP associative array or a JavaScript object (which is not an array).
So given this PHP:
You get this output:
Which alerts 62 when run.