checklist
checklist

Reputation: 12940

Jquery Parse JSON coming from an html element

I am trying to parse some JSON coming from the server into an object I can use in Javascript. The JSON is saved by the server inside a span. When I click on the action button, it should get the JSON and parse it into an object. Unfortunately, I get an exception. Please see the code:

$(function(){
  $("#btn").click(function(elem){
    var elem = $("#content");
    var html = elem.html();
    console.log(html);
    var x = JSON.parse(html);
    console.log(x);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <button id="btn">Action</button>
    <br/><br/>
     <span id="content">{"test" : "<a href=\"http://cnn.com\">CNN</a> Hello"}</span>
</body>

I also tried it with the content in the span not escaping the ":

<span id="content">{"test" : "<a href="http://cnn.com">CNN</a> Hello"}</span>

Any idea how to solve?

Note for background: this is used inside an angular app which needs to receive the json to init the model.

Upvotes: 2

Views: 3448

Answers (2)

Max Koretskyi
Max Koretskyi

Reputation: 105547

function parse() {
  var span = document.querySelector('span');
  console.log(JSON.parse(span.textContent));
}
<span id="content">{"test" : "&lt;a href=\"http://cnn.com\"&gt;CNN&lt;/a&gt; Hello"}</span>
<button onclick="parse()">parse</button>

The content inside your span

<span id="content">{"test" : "<a href="http://cnn.com">CNN</a> Hello"}</span>

should be escaped

<span id="content">{"test" : "&lt;a href=\"http://cnn.com\"&gt;CNN&lt;/a&gt; Hello"}</span>

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can pass html to JSON.stringify()

$(function(){
  $("#btn").click(function(elem){
    var elem = $("#content");
    var html = elem.html();
    console.log(html);
    var x = JSON.parse(JSON.stringify(html));
    console.log(x);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <button id="btn">Action</button>
    <br/><br/>
     <span id="content">{"test" : "<a href=\"http://cnn.com\">CNN</a> Hello"}</span>
</body>

Upvotes: 2

Related Questions