Search code examples
javascriptjsonencodingstringify

Using stringify on JSON object to use in HTML data attribute


I've been looking through the various on posts on stringify but I have been unable to find a solution to my problem.

I'm trying to stringify a JSON object and insert it into the data attribute of a new element in the DOM.

In the example below, if the element is inspected using Chrome and then edit HTML is selected, the output looks like the following:

<div class="ui-menu-item" data-menu-item="{" title":"this="" is="" a="" test="" for="" \"="" and="" '.="" it="" fails.","url":"some="" url"}"="" id="test">This element contains the data.</div>

The required result should look like the following I think:

<div class="ui-menu-item" data-menu-item="{&quot;title&quot;:&quot;this is a test for &quot; and ' it fails.&quot;,&quot;url&quot;:&quot;some url&quot;}" id="test">This element contains the data.</div>

Note: I know I can use jQuery's data method instead but choosing not to.

  var data = {
    title: 'This is a test for " and \'. It fails.',
	  url: 'Some url'
  };

  data = JSON.stringify(data);

  console.log (data);

$(document).ready(function() {
  var tpl = "<div class=\"ui-menu-item\" data-menu-item=\"" + data + "\" id=\"test\">This element contains the data.</div>";
  
  $('body').append(tpl);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
</body>
</html>


Solution

  •   var data = {
        title: 'This is a test for " and \'. It fails.',
    	  url: 'Some url'
      };
    
      data = JSON.stringify(data);
    
      console.log (data);
    
    $(document).ready(function() {
      var tpl = "<div class=\"ui-menu-item\" id=\"test\">This element contains the data.</div>";
      
      $('body').append(tpl);
      $('#test').attr('data-menu-item', data)
    });
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
    </body>
    </html>