Javascript JSON Date Deserialization

前端 未结 5 1955
轻奢々
轻奢々 2020-12-16 15:01

I am trying to deserialize a json object that has a javascript date in it. When JSON.stringify is called on the object, dates are serialized to strings that are not properl

5条回答
  •  没有蜡笔的小新
    2020-12-16 15:34

    You could manually add all of the Date functions you require to the String.prototype.

    String.prototype.getYear = function() {
        return Date.parse(this).getYear();
    };
    var obj = {date: new Date()};
    var dtObj = JSON.parse(JSON.stringify(obj));
    console.log(dtObj.date.getYear());
    

    Or you could override JSON.parse and have it loop through the result object looking for strings that match the time stamp regex and then convert them to Date objects.

    var JSON_parse = JSON.parse;
    JSON.parse = function(str) {
        var res = JSON_parse(str);
        findAndConvertStringsToDates(res);
        return res;
    } 
    

    EDIT Here's what I'd throw together for an implementation

    (function() {
        var jsonParse = JSON.parse;
        var reDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/i;
        function jsonDate(obj) {
            var type = typeof(obj);
            if(type == 'object') {
                for(var p in obj)
                    if(obj.hasOwnProperty(p))
                        obj[p] = jsonDate(obj[p]);
                return obj;
            } else if(type == 'string' && reDate.test(obj)) {
                return new Date(obj);
            } 
            return obj;
        }
        JSON.parse = function(str) { return jsonDate(jsonParse(str)); }
    })();
    /*
     * Tests
     */
    var dt = JSON.parse(JSON.stringify({date: new Date()}));
    console.log(typeof(dt.date));
    console.log(JSON.parse(JSON.stringify(null)));
    console.log(JSON.parse(JSON.stringify(123)));
    console.log(JSON.parse(JSON.stringify("test")));
    console.log(JSON.parse(JSON.stringify(new Date())));
    console.log(JSON.parse(JSON.stringify([1,new Date(),2])));
    console.log(JSON.parse(JSON.stringify({d: new Date(), d2: {d3: new Date(), d4: [0,new Date(),4]}})));
    

提交回复
热议问题