Reputation: 3804
Without using AJAX, how to correctly write a JSON string to JS from PHP. Example below, some case will break this code. I'm trying to find a perfect way to display json correctly, for both case "a" and "b"
Write the output JS to browser console, you'll see it breaks.
<?php
$var = array(
'nokey',
5 => 'xyz',
'key' => '456',
//bug
"apostrophe ' xx" => 'quotes " xx',
'\'' => "\"",
'malicious backslash \ ' => 'double \\',
"line break \n"
);
$var = json_encode($var);
?>
<script>
//bug
var a = JSON.parse('<?php echo $var ?>');
var b = JSON.parse("<?php echo $var ?>");
</script>
http://sandbox.onlinephpfunctions.com/code/5c860f978ddd6d196b15c58f55db20de34bcf72c
Upvotes: 0
Views: 59
Reputation: 1130
You dont need to parse a JSON object when it is already JSON.
remove JSON.parse()
<?php
$var = array(
'nokey',
5 => 'xyz',
'key' => '456',
//bug
"apostrophe ' xx" => 'quotes " xx',
'\'' => "\"",
'malicious backslash \ ' => 'double \\',
"line break \n"
);
$var = json_encode($var);
?>
<script>
//bug
var a = <?php echo $var ?>;
var b = <?php echo $var ?>;
</script>
Upvotes: 2
Reputation: 26527
You need to also addslashes()
.
$var = addslashes(json_encode($var));
Then, once outputted, it'll be output with it's quotes slashed, allowing it to be parsed properly.
It doesn't matter if you are using single-quotes ('') or double-quotes (""), you can slash all the quotes and it'll be just fine.
Upvotes: 1