cipher
cipher

Reputation: 2484

JSON.parse() works fine in console, but not inside HTML

Consider the following code:

JSON.parse('{"html":{"lang":"en"},"head":"\\n\\t<meta charset=\\"UTF-8\\">\\n\\t<title>Check ScreenShare</title>\\n\\t<link rel=\\"stylesheet\\" href=\\"main.css\\">\\n\\t<script src=\\"main.js\\"></script>\\n","body":"\\n\\t<h1>This is just a test</h1>\\n\\t<p>This is a great thing to do. This is very good.</p>\\n\\n\\n<script src=\\"sendContent.js\\"></script>"}');

This works fine in dev Console (firefox) but firefox shows error when i include this in a n html file like

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Check others</title>
</head>
<body>
    <!-- <iframe src="" frameborder="0" id="all"></iframe> -->
</body>
<script type="text/javascript">
    //var ifrm = document.getElementById('all');
    JSON.parse('{"html":{"lang":"en"},"head":"\\n\\t<meta charset=\\"UTF-8\\">\\n\\t<title>Check ScreenShare</title>\\n\\t<link rel=\\"stylesheet\\" href=\\"main.css\\">\\n\\t<script src=\\"main.js\\"></script>\\n","body":"\\n\\t<h1>This is just a test</h1>\\n\\t<p>This is a great thing to do. This is very good.</p>\\n\\n\\n<script src=\\"sendContent.js\\"></script>"}');
    //var obj = JSON.parse(JSONstr);
    console.log(obj);
</script> 
</html>

The error is:

SyntaxError: unterminated string literal

Anyone with idea how to make it work?

Upvotes: 4

Views: 363

Answers (2)

jyrkim
jyrkim

Reputation: 2869

Like Pointy and the following article suggests: "Escape the forward slash in HTML end tags. Hello World!</div>."

So I got it parsing correctly after adding three forward slashes to title tag and two script tags.

var object = JSON.parse('{"html":{"lang":"en"},"head":"\\n\\t<meta charset=\\"UTF-8\\">\\n\\t<title>Check ScreenShare<\/title>\\n\\t<link rel=\\"stylesheet\\" href=\\"main.css\\">\\n\\t<script src=\\"main.js\\"><\/script>\\n","body":"\\n\\t<h1>This is just a test</h1>\\n\\t<p>This is a great thing to do. This is very good.</p>\\n\\n\\n<script src=\\"sendContent.js\\"><\/script>"}');

console.log(object);

Upvotes: 1

Pointy
Pointy

Reputation: 413836

You can't embed the string </script> in a script block, because it ends the script block. The HTML parser doesn't know JavaScript syntax so it doesn't pay any attention to the quotes.

Use <\/script> instead.

I would further suggest that you look into a templating system, because embedding all that markup in a string is really messy and error-prone.

Upvotes: 5

Related Questions