I have a php nested array stored in a variable $myArray
, below is how the array looks like (its not a complete output) after var dumping it to the browser.
<?php var_dump($myArray); ?>
The output:
array (size=4)
'id' => string '162' (length=3)
'content' => string 'Test content' (length=12)
'children' =>
array (size=16)
0 =>
array (size=4)
'id' => string '29208' (length=5)
'content' => string 'Test content 1' (length=14)
'children' =>
array (size=3)
...
1 =>
array (size=4)
'id' => string '29215' (length=5)
'content' => string 'Test content 2' (length=14)
'children' =>
array (size=1)
...
2 =>
array (size=3)
'id' => string '29220' (length=5)
'content' => string 'Test Content 3' (length=14)
Reading the variable array from JavaScript as below:
<script type="text/javascript">
var myVar = JSON.parse('<?php json_encode($myArray) ?>');
</script>
Returns the following error in the console
Uncaught SyntaxError: Unexpected end of input
While debugging the code, I did the following:
Created a new variable and stored some JSON data in it and then JSON parsed it to another variable and then finally consoled the output and it worked fine.
<script type="text/javascript">
var x = '{"id":123,"content":"This is a test content"}';
var myVar = JSON.parse(x);
console.log(myVar);
</script>
The output was an object with those values in the console:
Object
content: "This is a test content"
id: 123
What am I doing wrong?