JSON.parse or alternative library that will also parse dates

北战南征 提交于 2020-01-15 11:45:30

问题


I'm using Json.NET to serialize some data. It is very flexible with how dates are serialized so I can output it to any format necessary.

Is there a date format that the browser provided JSON.parse function will deserialize into Date objects? If not, does anyone know of a good library that deserializes JSON into JavaScript objects, including dates?

I really don't want to have to use a RegExp and a whole bunch of ugly code to parse dates after deserializing the rest of the JSON; I just want a single function call that does the whole thing.


回答1:


Is there a date format that the browser provided JSON.parse function will deserialize into Date objects?

No. The standard has nothing regarding dates.

But the Date object now has a specific toJSON function defining de facto a standard for JSON date serialization. It's based on toISOString. See EcmaScript.

And the MSDN has a documentation on how to build a reviver for the standard JSON.parse function in order to get Dates back.

Extract :

var jsontext = '{ "hiredate": "2008-01-01T12:00:00Z", "birthdate": "2008-12-25T12:00:00Z" }';
var dates = JSON.parse(jsontext, dateReviver);
document.write(dates.birthdate.toUTCString());

function dateReviver(key, value) {
    var a;
    if (typeof value === 'string') {
        a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
        if (a) {
            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
        }
    }
    return value;
};

// Output:
// Thu, 25 Dec 2008 12:00:00 UTC

That's not exactly "a RegExp and a whole bunch of ugly code to parse dates after deserializing the rest of the JSON;", but rather a RegExp and a reasonable bunch of ugly but reusable code to parse dates during the deserialization...

The downside is that you can't distinguish between dates and strings that are the same as serialized dates. That makes the JSON format ambiguous, which is probably why JSON.parse doesn't venture into deserializing those dates normally.




回答2:


Why not var d = new Date(Date.parse(utcDateString)); ?



来源:https://stackoverflow.com/questions/15120256/json-parse-or-alternative-library-that-will-also-parse-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!