Skip to content

Instantly share code, notes, and snippets.

@mikeal
Created April 27, 2012 00:11
Show Gist options
  • Select an option

  • Save mikeal/2504336 to your computer and use it in GitHub Desktop.

Select an option

Save mikeal/2504336 to your computer and use it in GitHub Desktop.
Date parsing JSON
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);
}
@mikeal

mikeal commented Apr 27, 2012

Copy link
Copy Markdown
Author

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.

@polotek

polotek commented Apr 27, 2012

Copy link
Copy Markdown

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);
}

@mikeal

mikeal commented Apr 27, 2012

Copy link
Copy Markdown
Author

stealing.

@max-mapper

Copy link
Copy Markdown

i'd use JSON.dateyParse or JSON.timeyParse or something fun like that. think rachel ray: yummo! sammies!

@yocontra

Copy link
Copy Markdown

JSON.dateParsely fits standard naming convention

@visnup

visnup commented Apr 27, 2012 via email

Copy link
Copy Markdown

@mark-hahn

Copy link
Copy Markdown

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