0

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

3
  • use JSON_HEX_APOS and JSON_HEX_QUOT php.net/manual/en/json.constants.php Commented Nov 27, 2017 at 18:46
  • 2
    You don't need JSON.parse(); just embed it as raw JS code. Commented Nov 27, 2017 at 18:47
  • What is the problem by the way ? Try the outputed JSON into this tool : jsoneditoronline.org Commented Nov 27, 2017 at 18:47

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

In case the code is processed as xhtml I have seen as a common practice to surround code in the script tags as commented CDATA (//<![CDATA[ ... //]]>
This is correct. It covers all the cases without fail
1

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.

1 Comment

This is correct too. It works if I want a valid JSON string

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.