Reputation: 1455
I am retrieving values from server side code and here is my value ..
["INCOMING",09:09:49,"INETCALL",00:14:09,"ISD",00:05:50,"LOCAL",02:38:02,"STD",01:39:28]
Now as per my need i want to parse it into JSON but on parsing it is giving error..
SyntaxError: JSON.parse: expected ',' or ']' after array element
var dbdata=JSON.parse(data);
and here is my code to get value from server side and parse it into 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]);
}
}
});
Please guys help me. Thanks in advance..
Upvotes: 0
Views: 1382
Reputation: 21752
The value is not valid JSON nor is it valid JS. Every second elemt is invalid
E.g 09:09:49
is not valid it should (probably) be "09:09:49"
The below is a valid array and can be parsed with JSON.parse
["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]
an easy way to test these kinds of issues is to dump the server reply into the browser development console and see what errors if any that produce
Upvotes: 1
Reputation: 7302
Correct JSON Data:
// 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"
}
]';
Correct Ajax use with JSON:
// 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);
}
}
});
Conclusion:
You are using '$.isNumeric(dbdata[i])' but, as your json data your
first value is string. So it's not gonna to work.
Upvotes: 0
Reputation: 57
The value from your server isn't JSON fromat, it's array! The JSON format reference:https://developer.mozilla.org/en-US/docs/JSON
I think you should generate the data from your server like this:
[{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}]
Upvotes: 2
Reputation: 4063
You can test easily the validty of a JSON with this web tool:
Parse error on line 2:
... "INCOMING", 09: 09: 49, "INE
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
As bipen says, if you use PHP, send your data using json_encode(); and put json as datatype in your $.ajax
Upvotes: 0
Reputation: 10906
change your data to below format
["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]
Upvotes: 0