guub guub - 5 months ago 20
jQuery Question

Add attribute with JSON value

I want to add and store json in a

data-
attribute via jQuery.
Problem is: when I add the attribute containing the json and escaped double quotes, it's added with the exact
"
and not the escaped double quotes.

Output:

<div data-myjson="{&quot;number&quot;:&quot;1&quot;}"></div>


Expected: Browser should treat
&quot;
as double quotes and not as plain characters

<div data-myjson="{"number":"1"}"></div> // with escaped inner quotes


My jquery

$("div").attr("data-myjson", "{&quot;number&quot;:&quot;1&quot;}");


How can add actually escaped double quotes in the HTML itself?

Answer

Unless I'm misunderstanding, if the text containing the &quot; is a plain string as described above, the how about decoding it using:

var str = '{&quot;number&quot;:&quot;1&quot;}';
$("div").attr("data-myjson", $('<div/>').html(str).text());