jQuery data and JSON

jquery_logojQuery is picky about the JSON that is read from in HTML5 data elements. Of course, it’s not really jQuery that’s at fault, it’s simply that the JSON spec is a lot more strict than simple javascript.

In javascript, I can define an object like this:

var object = { look: "ma", no: "quotes" };

Note the lack of quotes on the key names in the object.

Since JSON is a data exchange specification, it requires quoted keys.

So, if you want to put JSON into a data element, you need to do this.

<span data-stuff='{"i":"need","the":"quotes"}'></span>

Here is the relevant quote from the JSON documentation:

“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.”