javascript - How to embed json with html control character entites in the html and let js consume that? -


i have use case need embed json in html , let javascript read it. example this:

<head></head> <body>     <div id="foo">{"foo": "bar&#xd;"}</div>     <script>         var = json.parse(document.getelementbyid('foo').innerhtml);         console.log(a);     </script> </body> </html> 

notice json has carriage return in &#xd; , because html parser convert entities original character, inner html javascript gets contain literal newline character, breaks json parse function call.

the solutions have:

  1. wrap content in cdata
  2. wrap content in script tag (this produce error parser saying syntax not valid seems working regardless)

question is: these approaches okay? if these not best practice, approach should used here?

encode & entity &amp;. , use textcontent raw content, without re-encoding & entity.

var = json.parse(document.getelementbyid('foo').textcontent);  alert(json.stringify(a));  console.log(a);
<div id="foo">{"foo": "bar&amp;#xc;"}</div>


Comments