Issue With JSON Data - javascript

I'm having a weird issue with some JSON data.
{
"title" : "Counties",
"data": [
{
"Name": "Baker",
"latlng": [
"44.65488,-118.42475",
"44.64548,-118.38275",
"44.62488,-118.34425",
"0,0",
"1,0"
]
}
]
}
When I use .getJSON for the file with this data I am getting an syntax error but if I take out the last two entries from the latlng array it will work correctly.
I put the JSON though the linter at jsonlint.com and it says it's valid JSON but chrome and firefox can't parse it for some reason.
The code that is getting the json file:
$(function() {
$.getJSON("json/counties.json", function(data){
console.log(data);
});
$(document).ajaxError(function(event, jqxhr, settings, exception){
console.log(exception);
});
});
The exception that is logged from Chrome
SyntaxError {}
And the exception that is logged from Firefox
[15:07:33.965] (new SyntaxError("JSON.parse: unexpected non-whitespace character after JSON data", "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js", 3))
As far as I can tell there aren't any characters after the JSON in the data, here's a screen shot

Your code is all working fine for me, and the data you're showing is fine, so there must just be something weird going on in your environment.
First thing I'd suggest is to watch your raw HTTP response in Fiddler or your browser's network tab, and see if there's anything unexpected there - maybe you've got a proxy server appending garbage to your data or something like that.
If not, then try opening up your counties.json file in a binary editor and look for any unexpected byte in there, maybe something invisible or a funky quotation mark or something. This is all ASCII here in your example, so it should be pretty easy to spot any character that doesn't belong.

Related

Codeigniter 4 enviroment make JSON.parse fail

I'm new in codeigniter 4
I just started a new project in Codeigniter 4, and i got an error using JSON.parse,
Unexpected token < in JSON at position 30
I get two different results from using different enviroments:
Default// did not make any change to codeigniter config
-The code run totaly fine, though for a second i manage to see a bug in console
-The bad thing, in this enviroment most of debugging tools are deactivated something that i would like to have while working.
SetEnv CI_ENVIRONMENT production // which makes the debugging tools from CI4 appear, this line is in .htacess
-The code stops at JSON.parse and get the error described before in console
So here it is how my code is estructured:
//controller
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//response rgets data from callback from a controller
console.log(response);//{status:0,message:'Access denied'}
data=JSON.parse(response); //error
//Other fixes i already tried
data=JSON.parse(JSON.stringify(response)); //Works fine, but returns a string, need an object
data=JSON.parse(JSON.parse(JSON.stringify(response))); //error
data=JSON.parse("{status:0,message:'Access denied'} "); //Even trying to use directly a JSON format throws error
data=JSON.parse({status:0,message:'Access denied'}) //error, without the comas
data=JSON.parse([{status:0,message:'Access denied'}]) //error
The debbuging tools seem to stop the loading when they find a bug, but i have not managed to find what i am doing wrong. Hope you can help me with this and thanks in advance.
EDIT
I´m using webix libraries for request, but they return string format.
I tried manually what you suggested,but the result was the same. It works if use CI4 in production env, but fails at development mode.
//Solutions tried
response = JSON.parse({"status":0,"message":"Access denied"});//error
response = JSON.parse("{'status':0,'message':'Access denied'}");//error
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//the response should be like this
{"status":0,"message":"Access denied"}
and then use like this
data=JSON.parse(response);
and kindly check your datatype during the post and it should be a json

Invalid JSON data $.get() method - Uncaught SyntaxError: Unexpected token <

I need help guys.
I am trying to fetch data from the server which is returning JSON data but I am getting the following error message (in Chrome 52).
It seems like the JSON data that is returned is invalid or its not in the expected format.
ncaught SyntaxError: Unexpected token <
My server is returning data in the following JSON format
"[{\"ActionCardId\":1,\"ActionCardNumber\":\"279877\",\"AccountNo\":\"2202322179\",\"ClientName\":null,\"CellNumber\":\"0787596971\",\"TenantName\":null,\"TenantCellNumber\":null,\"AddressStandNo\":null,\"AddressStreet\":\"43 DELMAS AVENUE\",\"AddressSuburb\":\"BOKSBURG\",\"AddressCity\":null,\"AddressPortion\":null,\"AddressEarthNo\":null,\"AddressPremise\":null,\"AddressGISKEY\":null,\"AmountDueTotal\":4080.0,\"AmountDue30Day\":null,\"AmountDueCurrent\":null,\"AmountDue60Day\":null,\"ServiceLevy\":null,\"MeterNumberWater\":null,\"MeterNumberElectricity\":\"M22541\",\"MeterNumberElectricity2\":null,\"MeterNumberElectricity3\":null,\"MeterNumberPrePaid\":null,\"IsPrinted\":true,\"IsResidential\":null,\"ActionSuccessful\":false,\"ActionCardDate\":\"2016-08-20T00:00:00\",\"Remarks\":null,\"UnSuccessfulReason\":null,\"CaptureContractorId\":null,\"AddressCombo\":\", 43 DELMAS AVENUE, BOKSBURG, , \",\"BillCycleName\":\"120\",\"ServiceIndicator\":null,\"WaterReading\":null,\"WaterReadingDate\":null,\"ElectricityReading\":null,\"ElectricityReadingDate\":null,\"Unit\":null,\"ActionCardTypeId\":2,\"ContractorId\":1,\"ActionCardStatusId\":1,\"UnSuccessfulActionReasonId\":null,\"TechnicianId\":1,\"AccountInfoId\":null,\"ServiceDeliveryCentreId\":4,\"BillCycleId\":2,\"ActionCardType\":{\"ActionCardTypeId\":2,\"Active\":null,\"CreatedByOnlineUserId\":null,\"DateCreated\":null,\"DateModified\":null,\"Deleted\":null,\"Description\":\"Electricity Disconnection\",\"ModifiedByOnlineUserId\":null,\"Name\":\"ED\",\"CreatedByUser\":null,\"ModifiedByUser\":null},\"Contractor\":null,\"ActionCardStatus\":null,\"UnSuccessfulActionReason\":null,\"Technician\":null,\"AccountInfo\":null,\"ServiceDeliveryCentre\":null,\"BillCycle\":null,\"ActionName\":\"ED\",\"DateCreated\":\"2016-07-06T00:00:00\",\"DateModified\":\"2016-08-13T10:24:17.5833635\",\"CreatedByOnlineUserId\":null,\"ModifiedByOnlineUserId\":\"fa93e65d-e4a7-4a0c-91c6-4561e2612f9c\",\"CreatedByUser\":null,\"ModifiedByUser\":null}]"
I am using Javascript in my client side
$("#importDailyJobs").click(function () {
var technicianId = 1;
var serverUrl = "http://localhost:35825/Mobile/ImportDailyReadings"
$.get(serverUrl, { TechnicianId: technicianId }, function (data, status) {
alert("Success");
console.log(data);
}, "jsonp");
});
I using jsonp because I am using cross domain to get the data.
Your returned data is not a JSON. It's a string. You explicitly expect JSON via the jsonp argument, and you return a string, hence the error.
It seems like you are encountering an error on that URL and the response is enclosed inside an html tag <>.
As suggested by "Jason P" you should check the actual response in the "raw" format. If you are on Google Chrome, you can press F12, then navigate to "Network" Tab, and then select "XHR" after which you should trigger the respective event by clicking on #importDailyJobs. You should see the Ajax Request, on clicking of which you shall be able to view the details for that request, like Headers, Preview, Response etc.
You can view the raw data inside the Response tab.
Also on a side note, just wrap the string in single quotes when you have double quotes inside it, and if you have both then wrap the string in the one which is least used, to prevent lots of escaping as can be seen in your sample response.

Strange issue with Json & PHP

There is any reason why a json string fail to be evaluated (transport.responseText.evalJSON();) on the server but works on my local installation ?
I'm doing a simple ajax request like this one:
new Ajax.Request(
this.saveUrl, {
method: 'post',
parameters: Form.serialize(this.form),
onLoading: function () {
totals.update('<div class="loading-ajax"> </div>');
},
onSuccess: function (transport) {
if (transport.status == 200) {
var data = transport.responseText.evalJSON();
totals.update(data.shipping_method);
}
},
onFailure: checkout.ajaxFailure.bind(checkout)
}
);
On server side I output an array containing some html:
$data = array(
'shipping_method' => $shipping_method,
'payment_method' => $payment_method
);
echo json_encode($data);
I have tried to valorize $total and '$other' as empty string '' but I get the same result:
transport.responseText.evalJSON(); return an "unexpected token"
As said above the weird thing is that on my local it works ( the output is the same as the server but js doesn't trigger any error )
I'm struggling with this almost all day ... any help is really appreciate thanks
UPDATE:
console.log(transport.responseText)
-> {"shipping_method":"","payment_method":""}
Inspecting the server response 'network tab' in chrome I can see a small difference, in comparison to my local: there is a small red dot before the response content if ( is say \ufeff if I move the mouse over it, I'm not sure about the meaning ... )
After some test I found out that the issue is encoding used in some PHP files, my co-worked had the brilliant idea to switch to ANSI. (ISO-8859)
For some reason these files coded with ANSI produced JSON content to be different:
chrome inspector was showing a red dot -> Byte_order_mark \ufeff character (aka BOM)
This probably means the BOM character is missing and this was breaking the json parse.
SOLUTION:
After I parsed and cleaned all my project files from the BOM character, chrome doesn't show the red dot in the inspector and the issue is gone
Still it is not clear why on my local installation the issue was not present while on the server it was ( both linux ) but there are probably multiple settings involved here ...
To clean your files see: Elegant way to search for UTF-8 files with BOM?
you can use map function to evaluate json value
$.map(transport, function (item){
totals.update(item.total);;
});
I think its Working fine

Js angular bug only on Safari

I have the following code:
$http.post(constants.path+'address.php', {form}).then(function(data){
console.log(data);
console.log("success");
});
}
Only on Safari I get the following error:
'SyntaxError: Unexpected token '}'. Expected a ':' following the property name 'form'.
Every other browser don't complain about this code. Any ideas ?
EDIT 1: The whole function is:
function enviaVaga(form){
console.log(form);
return $http.post(constants.path+'json.php', {form}).then(function(data){
console.log(data);
console.log("sucesso");
});
}
This is a service function to send data to my backend
EDIT2: Just for future reference, removing the {} created the problem that my backend was expecting to receive a form object on $formData, to solve this I use {form: form}, that works well on Safari.
You aren't passing anything valid for data. Safari is attempting to interpret {form} as a new object.
Other browsers may be more gracious, but just drop the { and }.
Actually, other browser might be interpreting {form} as object short notation which is not supported by safari. see: https://kangax.github.io/compat-table/es6/#object_literal_extensions

I keep getting "Uncaught SyntaxError: Unexpected token o"

I'm trying to learn some html/css/javascript, so I'm writing myself a teaching project.
The idea was to have some vocabulary contained in a json file which would then be loaded into a table. I managed to load the file in and print out one of its values, after which I began writing the code to load the values into the table.
After doing that I started getting an error, so I removed all the code I had written, leaving me with only one line (the same line that had worked before) ... only the error is still there.
The error is as follows:
Uncaught SyntaxError: Unexpected token o
(anonymous function)script.js:10
jQuery.Callbacks.firejquery-1.7.js:1064
jQuery.Callbacks.self.fireWithjquery-1.7.js:1182
donejquery-1.7.js:7454
jQuery.ajaxTransport.send.callback
My javascript code is contained in a separate file and is simply this:
function loadPageIntoDiv(){
document.getElementById("wokabWeeks").style.display = "block";
}
function loadWokab(){
//also tried getJSON which threw the same error
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
}
And my JSON file just has the following right now:
[
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
},
{
"english": "glasses",
"kana": "megane",
"kanji": "M"
}
]
Now the error is reported in line 11 which is the var glacier = JSON.parse(data); line.
When I remove the json file I get the error: "GET http://.../wokab.json 404 (Not Found)" so I know it's loading it (or at least trying to).
Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.
Further explanation can be found in Aditya Mittal's answer.
The problem is very simple
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
You're parsing it twice. get uses the dataType='json', so data is already in json format.
Use $.ajax({ dataType: 'json' ... to specifically set the returned data type!
Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.
Parsed data from jquery success handler for text/html response:
var parsed = JSON.parse(data);
Parsed data from jquery success handler for application/json response:
var parsed = data;
Another hints for Unexpected token errors.
There are two major differences between javascript objects and json:
json data must be always quoted with double quotes.
keys must be quoted
Correct JSON
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
}
Error JSON 1
{
'english': 'bag',
'kana': 'kaban',
'kanji': 'K'
}
Error JSON 2
{
english: "bag",
kana: "kaban",
kanji: "K"
}
Remark
This is not a direct answer for that question. But it's an answer for Unexpected token errors. So it may be help others who stumple upon that question.
Simply the response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o" however you have to specify datatype in your request to be of type dataType='json'
I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.
I was accessing the iframe data like this:
$('#load-file-iframe').contents().text()
which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to
$('#load-file-iframe').contents().find('body').text()
once I noticed some garbage in the HTML response.
Long story short check your raw HTML response data and you might turn something up.
SyntaxError: Unexpected token o in JSON
This also happens when you forget to use the await keyword for a method that returns JSON data.
For example:
async function returnJSONData()
{
return "{\"prop\": 2}";
}
var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);
will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.
To fix just add await as you're supposed to:
var json_str = await returnJSONData();
This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.
Make sure your JSON file does not have any trailing characters before or after. Maybe an unprintable one? You may want to try this way:
[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(tempActivity, getCircularReplacer());
Where tempActivity is fething the data which produces the error "SyntaxError: Unexpected token o in JSON at position 1 - Stack Overflow"

Categories

Resources