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..
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"}]
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
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"]
You can test easily the validty of a JSON with this web tool:
http://jsonlint.com/
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
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.
Related
I am trying to read the values of properties in this string, when i try to parse it , i get invalid character. Can you tell me whats wrong here
data = [{'title' : 'location 1','lat' : '29.769730','lng' : '-95.257181','desc' : 'Apartments',},{'title' : 'location 2','lat' : '29.852264','lng' : '-95.469999','desc' : 'location description',},];
var test = $.parseJSON(data)l
error - Unhandled exception at line 138, column 13 in http://localhost:17765/Loc/index
0x800a03f6 - JavaScript runtime error: Invalid character
In your code, data is not a string. It is an array. It does not need parsing (other than by the JavaScript compiler). Just discard $.parseJSON and work with the data.
data = [{'title' : 'location 1','lat' : '29.769730','lng' : '-95.257181','desc' : 'Apartments',},{'title' : 'location 2','lat' : '29.852264','lng' : '-95.469999','desc' : 'location description',},];
data.forEach(o => console.log(o.title));
It is being returned from an mvc5 controller method as a string
If your code does not accurately reflect the data you have and you do have a string, then it would need parsing.
The code you provided is, however, not valid JSON which:
Requires strings be quoted with " not '
Does not allow trailing , after the last item in an array.
You need to fix the server side code so it returns real JSON.
This will probably involve replacing some code which attempts to generate JSON by mashing together strings with some which uses a JSON aware library function (see this question).
Your JSON is invalid, try this:
var data = '[{"title" : "location 1","lat" : "29.769730","lng" : "-95.257181","desc" : "Apartments"},{"title" : "location 2","lat" : "29.852264","lng" : "-95.469999","desc" : "location description"}]';
var test = $.parseJSON(data);
validate your JSON here
[{"title" : "location 1","lat" : "29.769730","lng" : "-95.257181","desc" : "Apartments"},{"title" : "location 2","lat" : "29.852264","lng" : "-95.469999","desc" : "location description"}]
I have javascript function that calls an external Api and returns in most case a valid JSON string.
function (successResponse) {
{
console.log(successResponse);
}
However, in some cases it return the the following invalid JSON
Response: Status=200, Text: {"createdTime":"2017-05-08T14:47:56Z","lastUpdatedTime":"2017-05-08T14:47:56Z","createdMode":"API","uuid":"e333c1-3599-36d7-9ef5-dc22c79a4a52","userId":"anonymous"}, Error Message: null
How can I parse the above string to get the 'uuid'
Thanks
If you're expecting a response string in that format, you can use a regular expression to extract the "text" portion of the response:
function (successResponse) {
{
var responseText = successResponse.match(/\{.+\}/);
var responseTextJSON = JSON.parse(responseText);
var uuid = responseTextJSON.uuid;
console.log(uuid);
}
Maybe you can parse the string yourself to exclude everything outside of {} ?
var apiResponse = 'Response: Status=200, Text: {"createdTime":"2017-05-08T14:47:56Z","lastUpdatedTime":"2017-05-08T14:47:56Z","createdMode":"API","uuid":"e333c1-3599-36d7-9ef5-dc22c79a4a52","userId":"anonymous"}, Error Message: null';
var apiResponse_fixed = apiResponse.substring((apiResponse.indexOf("{") - 1), (apiResponse.lastIndexOf("}") + 1));
var json_obj = JSON.parse(apiResponse_fixed);
console.log(json_obj.uuid);
Replace the non-JSON features, and then interpret as JSON
Looks like the server owner has been a bit lazy, and programmed an error response which contains a JSON-like interior section but surrounded by a couple of non-JSON elements.
If you are desperate to resolve the situation and have no ability to fix the server output format, here is my suggestion:
notQuiteJson = 'Response: Status=200, Text: {"createdTime":"2017-05-08T14:47:56Z","lastUpdatedTime":"2017-05-08T14:47:56Z","createdMode":"API","uuid":"e333c1-3599-36d7-9ef5-dc22c79a4a52","userId":"anonymous"}, Error Message: null';
madeJson = notQuiteJson.replace('Response: Status=200, Text:','{"Response": {"Status":200}, "Text":').replace('Error Message: null','"ErrorMessage": null}')
obj = JSON.parse(madeJson)
console.log(obj.Text.uuid) // Result: "e333c1-3599-36d7-9ef5-dc22c79a4a52"
Of course this only works if the error message is always exactly this. In reality you may want to use a 3-digit wildcard to cover a range of "Status=" codes. But then you would have to also be confident that all the error modes produce the same non-JSON text at the start and end of the response.
Disclaimer
#sp00m and #Bergi, don't kill me: you are right of course, but this is just for if the poster has no choice in the matter 8-)
I am passing two JSON objects from jQuery - ajax call to servlet using JSON Stringify. But I am getting null. If I pass one Object I am getting expected data but I'm not able to receive two objects. Please help me to find my mistake.
$.ajax({
url : 'insertserv1',
type: 'POST',
dataType: 'json',
data: JSON.stringify({"test1" :masterdata,"test2" :InspTableArray}),
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
if (br != null) {
json = br.readLine();
}
System.out.println(json); // getting expected data as {"test1":{"grn":"55555","pono":"888888","row":1},"test2":["Type/,"As ","ok","ok","ok","ok","ok"]}
try {
JSONObject rawdata = new JSONObject(json);
JSONObject datat1 = rawdata.getJSONObject("test1");
JSONObject datat2 = rawdata.getJSONObject("test2");
System.out.println(datat1); // return nulls
System.out.println(datat2); // return nulls
The JSON that is being sent in the InspTableArray is invalid so when you try and parse it in Java it breaks:
{"test1":{"grn":"55555","pono":"888888","row":1},"test2":["Type/,"As ","ok","ok","ok","ok","ok"]}
// Problem is this character here --------------------------^
// which breaks the JSON Array of strings
// The value should be "Type" instead of "Type/
// and is likely causing a SyntaxError: Unexpected token A in JSON at position 66
test2 seems to be an array of strings, apart from the first element which isn't a String and causes the rest of the Array to break and should be:
"test2":["Type","As ","ok","ok","ok","ok","ok"]
// ^------ forward slash replaced with closing double-quotation mark
In Firebug net tab, in Response\Json tabs, I can see the value returned from CGI, using ajax:
I want to verify the exact characters values, so I can translate it into readable characters (and in the next step, store my values in the same encoding.)
How can I get this value in Javascript?
I tried to use encodeURI() on the ajax returned response, but I only got some [%EF%BF%BD] (the black-diamond-question-mark)
my JS code:
var jqxhr = $.ajax({
type: "GET",
url: AJAX_CGI_URL,
dataType : 'json',
cache: false,
data: { name: AJAX_PARAMS }
})
. . .
case "P_D":
for(var j = 0; j < varVal.length; j++) {
jj=j+1;
updateWidget("d" + jj, varVal[j]);
var res = encodeURI(varVal[j]);
console.log(jj + ": " + res);
} break;
=>
console log:
GET http://.../cgi-bin/xjgetvar.cgi ...
1: %EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%20%EF%BF%BD%EF%BF%BD%EF%BF%BD
which is actually => %EF%BF%BD %EF%BF%BD %EF%BF%BD %EF%BF%BD %20 %EF%BF%BD %EF%BF%BD %EF%BF%BD
[relates to my previous question - JavaScript encodes Hebrew string
I thought it will be easy to get the values Firebug shows. but it is not trivial :( ]
so my question now is - How can I get the same values Firebug gets ?!
I have the follow code, it's call a web service in other PC server.
Data parameters are ok.
"{ ControlId: 'ZAsociated_26037', TaskId: 1495613, UserId: 166396, TBodyId: ''}"
$.ajax({
type: "POST",
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ ControlId: '" + controlId + "', TaskId: " + taskid + ", UserId: " +
userId + ", TBodyId: '" + $(tbody).attr("id") + "'}",
url: getWSPath() + "/GetZAsociatedResults", // CARGAR AQUI LA DIRECCION DEL WEBSERIVCE
success: function (data) {
if (data != null && data.d != "[]") loadAsociatedTable(controlId, data.d);
$("#loadingImg" + controlId).remove();
},
error: function (xhr, ajaxOptions, thrownError) {
$("#loadingImg" + controlId).remove();
alert("Error al obtener los datos: " +thrownError + "\nCodigo de error: " +xhr.status);
}
});
The error is, that when i have the data.d result of WS, JSON add adicionals "\" chars in string:
The begin of response:
[{\"Nombre del Documento\":\"Indemnizacion/Factura. 22076 - Proveedor - Sin: 38653 Global: No\",\"Estado\":\"Pago finalizado\",
I try to replace "\" to null string but it doesnt work
This AJAX when success call to loadAsociatedTable function and this do:
for (var i = 0; i < $.parseJSON(data).length;i++){
and have an error in $.parseJSON(data).length because don't converter this string to object.
I checked in Chrome and the JSON is ok, without this bar "\", and recognize that like a object, the problem is in IE v.11 only.
Can you Post the complete JSON which will help me to analyze
In meanwhile try this
Using Eval on data.d like eval("{"+data.d+"}");
or JSON.Parse(data.d)
try validate you json here http://jsonlint.com/
The server's JSON response is invalid. Some server programmer has misunderstood JSON double quote escaping and tried to apply it everywhere. Have the server return valid JSON. Most server environments have standard JSON libraries which will construct JSON which is not invalid. The correct JSON is of course just
[{"Nombre del Documento":"Indemnizacion/Factura. 22076 - Proveedor - Sin: 38653 Global: No","Estado":"Pago finalizado", ...
You can try to fix the JSON yourself, by replacing \" with ", which would just be
replace(/\\"/g, '"')
but the problem is that you will also destroy \" sequences representing double quote marks inside string values. That's quite a tricky problem to solve. So the best solution is to get the server to send down correct JSON to start with.
Finally I could solve the problem, I used JSON.parse() instead $.parseJSON(), maybe is JQuery version. AJAX response contains this additionals "\" but when I parse this object, JS convert it without problems.
Thanks for your help!