Bug Tracker

Modify

Ticket #10863 (closed bug: fixed)

Opened 2 years ago

Last modified 20 months ago

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

Reported by: vickaita@… Owned by:
Priority: low Milestone: 1.8.1
Component: data Version: 1.7.1
Keywords: Cc:
Blocking: Blocked by:

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

comment:1 Changed 2 years ago by dmethvin

  • Priority changed from undecided to low
  • Status changed from new to open
  • Component changed from unfiled to ajax
  • Milestone changed from None to 1.next

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

comment:2 Changed 2 years ago by rwaldron

  • Component changed from ajax to data

comment:3 Changed 20 months ago by Dave Methvin

  • Status changed from open to closed
  • Resolution set to fixed

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

Changeset: 2263134b224fe03b90552369b5007220747fbaf0

comment:4 Changed 20 months ago by dmethvin

  • Milestone changed from 1.next to 1.8.1

Please follow the  bug reporting guidlines and use  jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

View

Add a comment

Modify Ticket

Action
as closed
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.