Quint Rahaman Quint Rahaman - 2 months ago 8
HTML Question

Get value from Object string added using .data()



$('#test').attr('data-mydata', "{'x-coord': 10}");

var myData = $('#test').data("mydata");
var x = myData['x-coord'];
console.log('x-coord: ' + x);


I want to attach to the div above the data noted above. When the code is executed, the DOM element, #test, is updated with the data which is great. Then I want to get the data out of the "object". However, mydata contains a string representation. How can this string be converted into an object? Bottom line: how can I get the key/value pairs out for further processing? JSON.parse does not seem to work. Thank you!

http://jsfiddle.net/quint/zyozqwv2/

Answer

JSON.parse does not seem to work

Well, that’s because it expects valid JSON.

{'x-coord': 10} isn’t valid JSON – it needs double quotes here, {"x-coord": 10}

And as soon as you fix that, you don’t need to parse it yourself any more, .data() will do that automatically:

$('#test').attr('data-mydata', '{"x-coord": 10}'); // switched quotes here

var myData = $('#test').data("mydata");
var x = myData['x-coord'];
console.log('x-coord: ' + x); // result: x-coord: 10

http://jsfiddle.net/zyozqwv2/1/

Comments