0

我正在从服务器端代码中检索值,这是我的值..

["INCOMING",09:09:49,"INETCALL",00:14:09,"ISD",00:05:50,"LOCAL",02:38:02,"STD",01:39:28]

现在根据我的需要,我想将其解析为 JSON,但在解析时会出错..

SyntaxError: JSON.parse: expected ',' or ']' after array element

var dbdata=JSON.parse(data);

这是我从服务器端获取值并将其解析为 json 的代码。

$.ajax({
                type: 'GET',
                url: 'getdataduration',
                async:false,
                dataType: "text",
                success: function(data) {

                    var dbdata=JSON.parse(data);

                    for(var i=0,len=dbdata.length;i<len;i++){
                        $.isNumeric(dbdata[i]) ?  callduration.push(dbdata[i]) :  toc.push(dbdata[i]);
                    }
                }

            });

请大家帮帮我。提前致谢..

4

5 回答 5

2

来自您服务器的值不是 JSON fromat,而是数组!JSON 格式参考:https ://developer.mozilla.org/en-US/docs/JSON

我认为您应该像这样从服务器生成数据:

[{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}]
于 2013-11-08T08:58:41.947 回答
1

该值不是有效的 JSON,也不是有效的 JS。每秒元素无效

例如09:09:49无效,它应该(可能)是"09:09:49"

下面是一个有效的数组,可以用 JSON.parse 解析

["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]

测试此类问题的一种简单方法是将服务器回复转储到浏览器开发控制台中,并查看是否产生了哪些错误

于 2013-11-08T08:52:55.017 回答
0

将您的数据更改为以下格式

  ["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]
于 2013-11-08T08:52:39.040 回答
0

您可以使用此 Web 工具轻松测试 JSON 的有效性:

http://jsonlint.com/

Parse error on line 2:
...    "INCOMING",    09: 09: 49,    "INE
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

正如 bipen 所说,如果您使用 PHP,请使用 json_encode(); 发送数据。并将 json 作为数据类型放入您的 $.ajax

于 2013-11-08T08:52:46.127 回答
0

正确的 JSON 数据:

// you should create your json like this
var data = '[{
        "INCOMING" : "09: 09: 49",
        "INETCALL" : "00: 14: 09",
        "ISD" : "00: 05: 50",
        "LOCAL" : "02: 38: 02",
        "STD" : "01: 39: 28"
    }
]';

正确使用 JSON 的 Ajax:

// use 'type: post' and 'dataType: json'. Because, post is safe and 
you are dealing with json data so it must be dataType: json
$.ajax({
    type : 'POST',
    url : 'getdataduration',
    async : false,
    dataType : "JSON",
    success : function (data) {
        var dbdata = JSON.parse(data);
        for (var i = 0, len = dbdata.length; i < len; i++) {
            $.isNumeric(dbdata[i].YOUR_JSON_KEY)
            ? callduration.push(dbdata[i].YOUR_JSON_KEY) 
            : toc.push(dbdata[i].YOUR_JSON_KEY);
        }
    }
});

结论:

You are using '$.isNumeric(dbdata[i])' but, as your json data your 
first value is string. So it's not gonna to work.
于 2013-11-08T09:46:15.690 回答