JSON.parse
ma mało znany drugi parametr: funkcję "reviver". Jest to używane dokładnie w tym celu: ożywić łańcuch daty w obiekcie Date
(lub hipotetycznie, każdy inny rodzaj obiektu, który chciałbyś przekonwertować z łańcucha) podczas początkowego analizowania.
Jest to SO post na ten temat, a oto blog post który zawiera przykładową implementację i funkcję, która zrobi nieruchomość sprawdzanie Kilka wspólny termin kodowania (ISO & że dziwne .NET Format AJAX), przed analizą do Date
.
Oto klucz funkcja z tego blogu, FWIW:
// JSON date deserializer
// use as the second, 'reviver' argument to JSON.parse();
if (window.JSON && !window.JSON.dateParser) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.dateParser = function (key, value) {
// first, just make sure the property is a string:
if (typeof value === 'string') {
// then, use regex to see if it's an ISO-formatted string
var a = reISO.exec(value);
if (a) {
// if so, Date() can parse it:
return new Date(value);
}
// otherwise, see if it's a wacky Microsoft-format string:
a = reMsAjax.exec(value);
if (a) {
// and perform some jujitsu to make use of it:
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
// here, you could insert any additional tests and parse instructions you like, for other date syntaxes...
}
// important: you need to return any values you're not parsing, or they die...
return value;
};
}
// use: JSON.parse(json,JSON.dateParser);
(Istnieje lots of opinions o odpowiednich regexes dla ISO 8601 terminach YMMV..Ponadto, nie ma żadnego szczególnego powodu, aby uderzyć funkcję w globalny obiekt JSON. Możesz przechowywać/odwoływać się w dowolnym miejscu.)
Dziękuję. Biblioteki te wydają się dodawać funkcje do dat, ale nie wydają się ulepszać/implementować analizatora składni json. – mdeangelo272