JSON throwing an error when it has a script tag embedded with the json

Viewed 121

Here is my script for testing purposes

<script>
var json = {
     "html": "<h3>COVID-19 Visitor Declaration</h3><script></script>"
};
</script>

That will throw a javascript error

Uncaught SyntaxError: Invalid or unexpected token

Now if I change the script to something else the error goes away

<script>
var json = {
     "html": "<h3>COVID-19 Visitor Declaration</h3><scripta></scripta>"
};
</script>

How can I let that script tag go through as valid JSON, guessing this is something to do with security.

2 Answers

You have to update your code to:

<script>
    var json = {
        "html": "<h3>COVID-19 Visitor Declaration</h3><script><\/script>"
    };
</script>

Escaped tag </script> is most important for that.

By using the Escape characters, for your closing tag <\/script>

var json = {
  "html":  "<h3>COVID-19 Visitor Declaration</h3><script><\/script>"
};


document.getElementById("html-content").innerHTML = json.html;
<div id="html-content"></div>

<scripta> works because it's not a valid tag for the browsers to evaluate and thus render it as normally on DOM.

When you pass <script>, browser parse it a valid HTML tag

var json = {
  "html":  "<h3>COVID-19 Visitor Declaration</h3><scripta>Test</scripta>"
};


document.getElementById("html-content").innerHTML = json.html;
<div id="html-content"></div>

Related