Side navigation
#10863 closed bug (fixed)
Opened November 22, 2011 07:01PM UTC
Closed August 24, 2012 02:20AM UTC
Last modified August 28, 2012 02:00AM UTC
.data method does not return an object if the JSON string contains newlines.
Reported by: | vickaita@gmail.com | 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.
Attachments (0)
Change History (4)
Changed November 22, 2011 07:10PM UTC by comment:1
component: | unfiled → ajax |
---|---|
milestone: | None → 1.next |
priority: | undecided → low |
status: | new → open |
Changed November 22, 2011 07:50PM UTC by comment:2
component: | ajax → data |
---|
Further reduction: http://jsfiddle.net/rwaldron/KC7sY/
Changed August 24, 2012 02:20AM UTC by comment:3
resolution: | → fixed |
---|---|
status: | open → closed |
Fix #10863. Allow newlines in JSON data- attributes.
Changeset: 2263134b224fe03b90552369b5007220747fbaf0
Changed August 28, 2012 02:00AM UTC by comment:4
milestone: | 1.next → 1.8.1 |
---|
Agreed, since
.*
generally doesn't match newline.