Skip to content

Commit

Permalink
Make empty strings (and other non-string values) simply return null f…
Browse files Browse the repository at this point in the history
…rom parseJSON. Also added some parseJSON tests. Fixes #5859.
  • Loading branch information
jeresig committed Jan 23, 2010
1 parent ea9e0ed commit 781fe8b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -472,25 +472,24 @@ jQuery.extend({
},

parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {

// Try to use the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
data = window.JSON.parse( data );

} else {
data = (new Function("return " + data))();
}
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();

} else {
jQuery.error( "Invalid JSON: " + data );
}

return data;
},

noop: function() {},
Expand Down
25 changes: 25 additions & 0 deletions test/unit/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -805,3 +805,28 @@ test("jQuery.proxy", function(){
// Use the string shortcut
jQuery.proxy( thisObject, "method" )();
});

test("jQuery.parseJSON", function(){
expect(7);

equals( jQuery.parseJSON(), null, "Nothing in, null out." );
equals( jQuery.parseJSON( null ), null, "Nothing in, null out." );
equals( jQuery.parseJSON( "" ), null, "Nothing in, null out." );

same( jQuery.parseJSON("{}"), {}, "Plain object parsing." );
same( jQuery.parseJSON('{"test":1}'), {"test":1}, "Plain object parsing." );

try {
jQuery.parseJSON("{a:1}");
ok( false, "Test malformed JSON string." );
} catch( e ) {
ok( true, "Test malformed JSON string." );
}

try {
jQuery.parseJSON("{'a':1}");
ok( false, "Test malformed JSON string." );
} catch( e ) {
ok( true, "Test malformed JSON string." );
}
});

1 comment on commit 781fe8b

@DBJDBJ
Copy link

@DBJDBJ DBJDBJ commented on 781fe8b Jan 25, 2010

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jQuery.parseJSON()
If you have time and if you think this is usefull: http://dbj.org/dbj/?p=470, please feel free to use.

Please sign in to comment.