如何使用JSON。parse reviver参数来解析日期字符串。

时间:2021-12-18 06:47:01

My JSON string contains a date field that returns such a value:

我的JSON字符串包含一个返回值的日期字段:

"2009-04-04T22:55:16.0000000-04:00"

I am particularly interested in parsing only the date compartment not the time. I tried using a reviver function, but interestingly the reviver function is never invoked! (tried on Firefox)

我特别感兴趣的是只解析日期间隔,而不是时间。我尝试使用了一个恢复函数,但有趣的是,恢复函数从来没有被调用过!(试穿Firefox)

Here is my code to accomplish that:

下面是我的代码:

var Site = {
.....
dateReviver: function(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;
},
loadArticle: function(id) {
....
    proxy.getArticle(id, function(response) {
        var data = JSON.parse(response.result, Site.dateReviver);
        ....
    });
}
};

JSON.parse in loadArticle never calls dateReviver.

JSON。在loadArticle中解析从不调用dateReviver。

I invested a whole day but no luck! Could someone please help me?

我花了一整天的时间,但是没有运气!有人能帮我吗?

5 个解决方案

#1


4  

  1. The regular expression expects a "Zulu" timezone (A 'Z' character at the end), while the sample date-time string shows a numeric timezone ('-04:00'). The following regex will accept both:

    正则表达式期望一个“祖鲁”时区(末尾的“Z”字符),而示例日期时间字符串显示一个数字时区('-04:00')。以下的regex将同时接受:

    /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/
    

    If the time zone digits are not zero, you might want to actually modify the date after parsing and/or converting to UTC, to respect the timezone.

    如果时区数字不为零,那么您可能想要实际修改解析和/或转换到UTC后的日期,以尊重时区。

  2. I can see dateReviver() being hit. Try the following in a browser:

    我可以看到dateReviver()被击中。在浏览器中尝试以下操作:

    <!-- saved from url=(0014)about:internet -->
    <html>
        <head>
            <script src="http://www.json.org/json2.js"></script>
            <script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js"></script>
            <script>
                $(function () {
                    // a mock proxy to return some json to play with
                    var proxy = {
                        getArticle: function(id, foo) { foo({
                            result: '["2009-04-04T22:55:16.0000000-04:00"]'
                        }); }
                    };
                    // the origial Site object, with the fixed regex
                    var Site = {
                        dateReviver: function(key, value) {
                            var a;
                            if (typeof value === 'string') {
                                a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/.exec(value);
                                if (a) {
                                    return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                                                    +a[5], +a[6]));
                                }
                            }
                            return value;
                        },
                        loadArticle: function(id) {
                            proxy.getArticle(id, function(response) {
                                var data = JSON.parse(response.result, Site.dateReviver);
                                // put the parsed JSON date on the page
                                $("#output").html(data[0].toString());
                            });
                        }
                    };
                    // try out our Site object
                    Site.loadArticle();
                });
            </script>
        </head>
        <body>
            <div id="output"></div>
        </body>
    </html>
    

    I am getting the following in the browser, indicating successful parsing:

    我在浏览器中得到以下信息,表明成功的解析:

    Sat Apr 4 15:55:16 PDT 2009
    

#2


4  

Using TypeSript, my solution is as follows:

使用TypeSript,我的解决方案如下:

    export function parseWithDate(jsonString: string): any {
    var reDateDetect = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;  // startswith: 2015-04-29T22:06:55
    var resultObject = JSON.parse(jsonString,(key: any, value: any) => {
        if (typeof value == 'string' && (reDateDetect.exec(value))) {
            return new Date(value);
        }
        return value;
    });
    return resultObject;
}

Best of all worlds ;-) It uses an anonymous datereviver, which gets called by JSON.parse on each property. The reviver logic is to check whether the property is of type string and if so, whether it looks like the start of a date ... If it is a date, then let new Date(value) do the actual parsing ... all timezone variations are supported that way.

它使用一个匿名的datereviver,它被JSON调用。解析每个属性。修改器逻辑是检查属性是否为string类型,如果是,是否看起来像日期的开始…如果是日期,那么让新的日期(值)执行实际的解析…所有时区的变化都是这样支持的。

Hope it helps!

希望它可以帮助!

#3


3  

Extending the jQuery.ajax converters setting worked fine for me from its's default:

延长jQuery。ajax转换器的设置对我来说很好用:

"text json": jQuery.parseJSON

to

"text json": function (xmlValue) {
            var value = JSON.parse(xmlValue, Site.dateReviver);
      return value;
      } 

#4


2  

The use of return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));

使用返回新日期(日期。UTC(+[1],[2]- 1,+一个[3]+[4],[5]+,+[6]));

does not adjust the date for the timezone information, the -4:00 in the example.

不调整时区信息的日期,在示例中为-4:00。

An alternative is to let Date() do the parsing for you:

另一种方法是让Date()为您进行解析:

var dateReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = Date.parse(value);
        if (a) {
            return new Date(a);
        }    
    }
    return value;
}

If the JSON had been formatted with JSON.stringify() it would have been in UTC (Z).

如果JSON被格式化为JSON.stringify(),那么它将在UTC (Z)中。

#5


0  

function dateReviver (k,v) {

    var isnum = /^\d+$/.test(v);

    // Check if number since Date.parse(number) returns valid date
    if (isnum) {
        return v;
    }

    if (Date.parse(v)) {
        return new Date(Date.parse(v));
    }
    return v;
}

#1


4  

  1. The regular expression expects a "Zulu" timezone (A 'Z' character at the end), while the sample date-time string shows a numeric timezone ('-04:00'). The following regex will accept both:

    正则表达式期望一个“祖鲁”时区(末尾的“Z”字符),而示例日期时间字符串显示一个数字时区('-04:00')。以下的regex将同时接受:

    /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/
    

    If the time zone digits are not zero, you might want to actually modify the date after parsing and/or converting to UTC, to respect the timezone.

    如果时区数字不为零,那么您可能想要实际修改解析和/或转换到UTC后的日期,以尊重时区。

  2. I can see dateReviver() being hit. Try the following in a browser:

    我可以看到dateReviver()被击中。在浏览器中尝试以下操作:

    <!-- saved from url=(0014)about:internet -->
    <html>
        <head>
            <script src="http://www.json.org/json2.js"></script>
            <script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js"></script>
            <script>
                $(function () {
                    // a mock proxy to return some json to play with
                    var proxy = {
                        getArticle: function(id, foo) { foo({
                            result: '["2009-04-04T22:55:16.0000000-04:00"]'
                        }); }
                    };
                    // the origial Site object, with the fixed regex
                    var Site = {
                        dateReviver: function(key, value) {
                            var a;
                            if (typeof value === 'string') {
                                a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/.exec(value);
                                if (a) {
                                    return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                                                    +a[5], +a[6]));
                                }
                            }
                            return value;
                        },
                        loadArticle: function(id) {
                            proxy.getArticle(id, function(response) {
                                var data = JSON.parse(response.result, Site.dateReviver);
                                // put the parsed JSON date on the page
                                $("#output").html(data[0].toString());
                            });
                        }
                    };
                    // try out our Site object
                    Site.loadArticle();
                });
            </script>
        </head>
        <body>
            <div id="output"></div>
        </body>
    </html>
    

    I am getting the following in the browser, indicating successful parsing:

    我在浏览器中得到以下信息,表明成功的解析:

    Sat Apr 4 15:55:16 PDT 2009
    

#2


4  

Using TypeSript, my solution is as follows:

使用TypeSript,我的解决方案如下:

    export function parseWithDate(jsonString: string): any {
    var reDateDetect = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;  // startswith: 2015-04-29T22:06:55
    var resultObject = JSON.parse(jsonString,(key: any, value: any) => {
        if (typeof value == 'string' && (reDateDetect.exec(value))) {
            return new Date(value);
        }
        return value;
    });
    return resultObject;
}

Best of all worlds ;-) It uses an anonymous datereviver, which gets called by JSON.parse on each property. The reviver logic is to check whether the property is of type string and if so, whether it looks like the start of a date ... If it is a date, then let new Date(value) do the actual parsing ... all timezone variations are supported that way.

它使用一个匿名的datereviver,它被JSON调用。解析每个属性。修改器逻辑是检查属性是否为string类型,如果是,是否看起来像日期的开始…如果是日期,那么让新的日期(值)执行实际的解析…所有时区的变化都是这样支持的。

Hope it helps!

希望它可以帮助!

#3


3  

Extending the jQuery.ajax converters setting worked fine for me from its's default:

延长jQuery。ajax转换器的设置对我来说很好用:

"text json": jQuery.parseJSON

to

"text json": function (xmlValue) {
            var value = JSON.parse(xmlValue, Site.dateReviver);
      return value;
      } 

#4


2  

The use of return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));

使用返回新日期(日期。UTC(+[1],[2]- 1,+一个[3]+[4],[5]+,+[6]));

does not adjust the date for the timezone information, the -4:00 in the example.

不调整时区信息的日期,在示例中为-4:00。

An alternative is to let Date() do the parsing for you:

另一种方法是让Date()为您进行解析:

var dateReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = Date.parse(value);
        if (a) {
            return new Date(a);
        }    
    }
    return value;
}

If the JSON had been formatted with JSON.stringify() it would have been in UTC (Z).

如果JSON被格式化为JSON.stringify(),那么它将在UTC (Z)中。

#5


0  

function dateReviver (k,v) {

    var isnum = /^\d+$/.test(v);

    // Check if number since Date.parse(number) returns valid date
    if (isnum) {
        return v;
    }

    if (Date.parse(v)) {
        return new Date(Date.parse(v));
    }
    return v;
}