I have JSON coming from my server into my javascript like so –
<script>
var resp = <?php echo getjsonFromServer() . ';'?>
resp=JSON.parse(resp);
displayStats(resp);
</script>
This yields an error ‘SyntaxError: Unexpected token o’ and when I check the console I see that the response has already been JSON parsed . Meaning I shouldn’t have tried to JSON.parse an already parsed answer .
My question is – how come ? Who parsed my JSON for me ? I’m used to call JSON.parse whenever I get JSON from the server , e.g ajax calls . Why is it not the same here ?
Note – My PHP is something like this
header('"Content-Type":application/json');
$js = json_encode($js);
echo $js;
Look at your generated source.
You’re echoing raw JSON, so your source looks like
That’s an object literal, not a string