I store JSON in a data
attribute, which contains "
:
<div id="tt" data-json='{"t":"title: "BB""}'></div>
I get the data-json
value with jQuery:
aa1 = $('#tt').data('json');
However, I get a string aa1
, not an object as I would expect. If I delete "
from the JSON, then I get an object in aa1
.
If I do so:
aa1_str = $('#tt').attr('data-json');
aa1 = JSON.parse(aa1_str);
I am getting an error in JSON.parse:
Uncaught SyntaxError: Unexpected token B in JSON at position 14
$('#tt').attr('data-json')
returns an already parsed string, where "
is replaced with "
.
How can I correctly extract data from a JSON string which contains "
?
CodePudding user response:
The problem is that the "
HTML entity gets decoded to a "
before jQuery can parse the object. This turns the value in to {"t":"title: "BB""}
, which is not a valid JSON string, hence jQuery does not parse it to an object for you and returns the original string.
To correct this you can use other HTML entities to encode the quotes, such as “
and ”
or “
and ”
, the latter of which I used in the following working example:
let aa1 = $('#tt').data('json');
console.log(aa1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tt" data-json='{"t":"title: “BB”"}'></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
That being said, I would suggest a different approach; remove the need for the quotes at all. Just return the BB
value in the title property and format the output to include title:
in the UI, if necessary. For example:
<div id="tt" data-json='{"title": "BB"}'></div>
CodePudding user response:
Maybe you can use decodeURIComponent
https://www.w3schools.com/jsref/jsref_decodeuricomponent.asp
aa1_str = $('#tt').attr('data-json');
var uri_enc = encodeURIComponent(aa1_str); // before you save the content
console.log(uri_enc);
var uri_dec = decodeURIComponent(aa1_str); // before you display the content
$("#test").text(uri_dec);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tt" data-json='{"t":"title: "BB""}'></div>
<div id="test"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I believe the problem is with your syntax in the attribute. JavaScript is, to my knowledge, unable to distinguish "
form "
. Hence when you get the attribute, what is returned is: {"t":"title: "BB""}
. This cannot be a valid JSON.
My suggestion is to escape using simple backslash instead of special character escapes. So,
HTML
<div id="tt" data-json='{"t":"title: \"BB\""}'></div>
JQUERY
var aa1 = $('#tt').attr('data-json');
var jsonAa1 = JSON.parse(aa1);
Now jsonAa1
is a valid JSON object that you can use as you please.