How to pass an array into jQuery .data() attribute

It's treating your variable as a string, the zeroth element of which is [.

This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.

If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)

<div data-stuff='["a","b","c"]'> </div>

var stuff = $('div').data('stuff');

When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.


Declaring it as an attribute means that it is a string.

So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);

You need to make it look like this:

<div data-stuff="a,b,c"></div>

var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);

Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.

However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.