Bug Tracker

Opened 11 years ago

Closed 10 years ago

Last modified 10 years ago

#10863 closed bug (fixed)

.data method does not return an object if the JSON string contains newlines.

Reported by: [email protected] Owned by:
Priority: low Milestone: 1.8.1
Component: data Version: 1.7.1
Keywords: Cc:
Blocked by: Blocking:


I am attempting to use the .data method to retrieve a JSON object that was stored in a data attribute on an element. If there are newlines present in the data attribute then the .data method will return a string instead of an object. If the newlines are removed then an object will be returned.

I have created a JSFiddle that demonstrates this behavior: http://jsfiddle.net/vickaita/5hy6Y/

It seems that there is a regexp that is used to test the value of the data attribute to see if it should be passed to jQuery.parseJSON. It is defined on line 3 of src/data.js

var rbrace = /(?:\{.*\}|\[.*\])$/,

I believe that the .* portions of this regexp are not matching the newline characters in the attribute. Replacing them with [\s\S] seems to fix this issue. [\s\S] should match whitespace and non-whitespace characters. The new regexp would be:


In a production site the whitespace would normally be stripped out, but during development it can be useful to pretty print the JSON in a data attribute with newlines.

Change History (4)

comment:1 Changed 11 years ago by dmethvin

Component: unfiledajax
Milestone: None1.next
Priority: undecidedlow
Status: newopen

Agreed, since .* generally doesn't match newline.

comment:2 Changed 11 years ago by Rick Waldron

Component: ajaxdata

comment:3 Changed 10 years ago by Dave Methvin

Resolution: fixed
Status: openclosed

Fix #10863. Allow newlines in JSON data- attributes.

Changeset: 2263134b224fe03b90552369b5007220747fbaf0

comment:4 Changed 10 years ago by dmethvin

Milestone: 1.next1.8.1
Note: See TracTickets for help on using tickets.