Tim
Tim

Reputation: 2163

HTML entities converted into their character values when JSON read from data attribute

I'm trying to access a stringified JSON array in a data attribute. When I grab the value with $(...).data('whatever') or $(...).attr('data-whatever'), however, HTML entities (e.g. ") in the content of the JSON get converted to their character representation (e.g. ") which causes the JSON string to be misinterpreted when parsed.

For example, if the value of my data attribute is ["Oberlin City Club: Opera Preview","Documentary Screening "Still Dreaming: Frances Walker at 93""], reading this with $(...).data() returns ["Oberlin City Club: Opera Preview","Documentary Screening "Still Dreaming: Frances Walker at 93""]. Why did JavaScript convert " into "? How can I read the data attribute without converting " into "?

console.log($('div').attr('data-titles'));
console.log(JSON.parse($('div').attr('data-titles')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-titles='["Oberlin City Club: Opera Preview","Documentary Screening &quot;Still Dreaming: Frances Walker at 93&quot;"]'></div>

Upvotes: 2

Views: 758

Answers (1)

Travis J
Travis J

Reputation: 82287

Why did JavaScript convert &quot; into "?

In this case, it didn't. By using &quot; in your response, the browser parses that as " and that is what gets put into the attribute. This is because you used an html entity.

An HTML entity is a piece of text ("string") that begins with an ampersand (&) and ends with a semicolon (;) Entity MDN

As a result, there is no chance for JavaScript to remedy this situation. You need to figure out a way to render the &quot; differently in your templating engine, ideally double-encoding the quote with &amp;quot; (as mentioned by @Barmar in comments).

Upvotes: 2

Related Questions