Created
April 27, 2012 00:11
-
-
Save mikeal/2504336 to your computer and use it in GitHub Desktop.
Date parsing JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
JSON._dateReviver = function (k,v) { | |
if (v.length !== 24 || typeof v !== 'string') return v | |
try {return new Date(v)} | |
catch(e) {return v} | |
} | |
JSON.parseWithDates = function (obj) { | |
return JSON.parse(obj, JSON._dateReviver); | |
} |
yeah, I wouldn't either. I'd just use it on json I'd suspect has dates in it so that I wouldn't have to individually Date.parse
them afterwards.
@polotek, good point though.
what i was trying to say was, if you override it globally and then use someone else's library which internally uses JSON.parse they will get results they are not expecting, which would be very bad. if you want it to be this way in your code just always use this JSON function but don't override the global.
How's this?
JSON._dateReviver = function (k,v) {
if (v.length !== 24 || typeof v !== 'string') return v
try {return new Date(v)}
catch(e) {return v}
}
JSON.parseWithDates = function (obj) {
return JSON.parse(obj, JSON._dateReviver);
}
stealing.
i'd use JSON.dateyParse
or JSON.timeyParse
or something fun like that. think rachel ray: yummo! sammies!
JSON.dateParsely
fits standard naming convention
`JSON.parseyDate`? kinda like parsley and dates!
On Apr 26, 2012, at 7:13 PM, Max [email protected] wrote:
i'd use `JSON.dateyParse` or `JSON.timeyParse` or something fun like that. think rachel ray: yummo! sammies!
…---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2504336
How about dateify? I've always thought stringify was weird so why not keep up the tradition?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure, it's a judgment call. But if most of the json you're parsing has dates and you use dates a lot and you want them to be date objects, this is way better than always wondering which one you should use.