douglascrockford / JSON-js

JSON in JavaScript
http://www.JSON.org/
8.7k stars 4.59k forks source link

Fix JSON.stringify(new Date(NaN)) in Safari #68

Closed benjaminoakes closed 7 years ago

benjaminoakes commented 9 years ago

I recently found that Safari's JSON.stringify doesn't handle invalid dates correctly, leading to an exception that would stop the execution of code, unlike other browsers. A bug similar to the below example made it into our production system because Safari wasn't tested exhaustively. This pull request works around the bug in Safari so that it behaves like Chrome, Firefox, etc. The bug is present in all versions of Safari that I had available to test.

Example situation:

var s, numberOfDaysFromUserInput = NaN; // Imagine this came from a form field

s = JSON.stringify({
    name: "John Doe",
    tasks: [
        {
            title: "Take out the recycling",
            due_date: new Date((new Date()).getTime() + 1000 * 60 *
                60 * 24 * numberOfDaysFromUserInput)
        }
    ]
});

doSomethingWith(s);
danbernier commented 9 years ago

I've seen this issue, too.

I like this fix: take it for a test-drive, and if it breaks, fall back on the known commodity. And the comments will help us remember, 10 years from now, why the code is here.

:+1:

benjaminoakes commented 7 years ago

This seems to be fixed on Safari Version 10.0.2 (11602.3.12.0.1), though older iOS and macOS installations would still be affected.