JSON 中的日期对象返回的数据被视为字符串

Date object in JSON return data treated as string

本文关键字:数据 字符串 返回 日期 对象 JSON      更新时间:2023-09-26

我尝试从URL获取JSON数据并将值推送到函数中。所有 JSON 值都用引号括起来,以具有正确的 JSON 格式。但实际上并非所有值都是字符串。

下面是一个 JSON 示例:

table = [
          {
            'date1': 'new Date(2015,13,1)',
            'content': 'this is the content'
          },
          {
            'date1': 'new Date(2015,13,2)',
            'content': 'this is the contentB'
          }
];

文件加载方式如下:

var req = new XMLHttpRequest();
var url = "http://localhost/json-test";
req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
            var myData = JSON.parse(req.responseText);
            drawFunction(myData);
        }
 }
  req.open("GET", url, true);
  req.send();
  function drawFunction(myData) {
      doSomething();            
  }

这有效 - 但"新日期"值(当然)也作为字符串返回。如何转换它们?该函数应使用如下值:

table = [
          {
            'date1': new Date(2015,13,1), //as new Date - not as string - without quotes
            'content': 'this is the content'
          },
          {
            'date1': new Date(2015,13,2),
            'content': 'this is the contentB'
          } ];

我可能完全错了。任何提示将不胜感激。无法更改 JSON 源文件。

您的错误是new Date对象周围''字符的包围。他们将其作为字符串发送,而不是评估对象。

写这个,

'date1': (new Date(2015,13,1)).toString()

而不是

'date1': 'new Date(2015,13,1)'

这将以标准格式返回日期。它也可以格式化。

注意:您不能通过 JSON 发送自定义对象(如 Date),只能发送经过评估的字符串。(仅仅因为JSON是一个独立于平台的交易所)