#10863 closed bug (fixed)
.data method does not return an object if the JSON string contains newlines.
Reported by: | Owned by: | ||
---|---|---|---|
Priority: | low | Milestone: | 1.8.1 |
Component: | data | Version: | 1.7.1 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
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:
/(?:\{[\s\S]*\}|\[[\s\S]*\])$/
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
Component: | unfiled → ajax |
---|---|
Milestone: | None → 1.next |
Priority: | undecided → low |
Status: | new → open |
comment:2 Changed 11 years ago by
Component: | ajax → data |
---|
Further reduction: http://jsfiddle.net/rwaldron/KC7sY/
comment:3 Changed 10 years ago by
Resolution: | → fixed |
---|---|
Status: | open → closed |
Fix #10863. Allow newlines in JSON data- attributes.
Changeset: 2263134b224fe03b90552369b5007220747fbaf0
comment:4 Changed 10 years ago by
Milestone: | 1.next → 1.8.1 |
---|
Agreed, since
.*
generally doesn't match newline.