Sami Al-Subhi
Sami Al-Subhi

Reputation: 4662

Converting string obtained from element's data attribute to json

I get an error with the following code. I know $.parseJSON() is sensitive to single/double quotes. I cannot think of a solution to this problem. Can you please help !

<div data-x='{"a":"1","b":"2"}'></div>

$(document).ready(function(){
    var data =$.parseJSON($("div").data("x"))
    alert(data.a)
})

https://jsfiddle.net/r2Lnfbpm/

Upvotes: 1

Views: 61

Answers (1)

adeneo
adeneo

Reputation: 318182

jQuery's data() does type conversion, so when the data attribute is valid JSON, it's already parsed into an object, and passing an object to $.parseJSON produces an error, as it expects a string of JSON.

$(document).ready(function(){
    var data = $("div").data("x");
    console.log(data.a);
});

From the documentation

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).
A value is only converted to a number if doing so doesn't change the value's representation.

For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.

To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

Upvotes: 3

Related Questions