An error while parsing JSON in JQuery - javascript

Tried to parse JSON with JQuery:
$.getJSON('php/getchannelstat.php?id=57', function(myarray) {
The file is:
{"label":"Test","data":[[1469037397,2],[1469037400,2],[1469037601,2],[1469039401,4],[1469041201,5],[1469043001,5],[1469044801,5],[1469113202,3],[1469115001,3],[1469115998,4],[1469116218,3],[1469116266,3],[1469116281,3],[1469116297,3],[1469116322,3],[1469116330,3],[1469116801,3],[1469118601,4],[1469120401,3],[1469122201,4]] }
Can't find any syntax errors, but it says:
Unexpected token ] in JSON at position 324
(in the last symbols)
What can be wrong with this?

Related

Uncaught SyntaxError: Unexpected token X in JSON from API response

I have the following valid json (partially shown), which I have received as a response to an HTTP request (I don't control the server):
"TotalResults":2,"SearchTerm":"XX","SearchTermClean":"XX","SearchTermExact":"\"XX\"","SearchTermNonExact":"XX","Page":1,"PageSize":100,"TotalPages":1,"TotalTime":0.072,"Filter":"","Sort":"","SortClean":"","IsDesc":false,"PreviousPage":1,"NextPage":1}'
I'm trying to parse this JSON using:
var json_obj= JSON.parse(helpers.testJSON());
where testJSON returns an entire string of json.
I'm getting:
Uncaught SyntaxError: Unexpected token X in JSON at position 1685
which translates to:
":"\"XX\""
How can I fix this error? I assume I would need to preprocess the JSON before using JSON.parse
There is an error in your example. You are using double quotes inside the string. To fix this, you need to escape them with \
So your JSON will look like this:
{
"Results":2,
"SearchTerm":"XX",
"SearchTermClean":"XX",
"SearchTermExact":"\"XX\"",
"SearchTermNonExact":"XX",
"Page":1,
"PageSize":100,
"TotalPages":1,
"TotalTime":0.072,
"Filter":"",
"Sort":"",
"SortClean":"",
"IsDesc":false,
"PreviousPage":1,
"NextPage":1
}
For easy detection of errors in JSON syntax, beautify and other useful actions, you can use this tool

Android hybrid app gives me "Uncaught SyntaxError: Unexpected identifier", source: (1)

I received a valid JSON from the server, but Chromium tells me this error:
"Uncaught SyntaxError: Unexpected identifier", source: (1)
All I know is that when I call the following method:
stringBuilder.append("javascript: javascriptBridge.getHandlers().showPost('");
stringBuilder.append(e.getData());
stringBuilder.append("');");
webView.loadUrl(stringBuilder.toString());
Where e.getData() is the valid JSON, it doesn't actually get called on the other side. Something in the JSON is interpreted incorrectly as a javascript function parameter
javascriptBridge.registerHandler('showPost', function (data) {
alert('showpost'); //this is not called
});
It works for other datas and it worked previously even for JSON, that is why it's odd. Any ideas how to fix it? It's probably some character that crashes it.
The following fixed it, thanks to commons-lang3:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("javascript: javascriptBridge.getHandlers().showPost('");
stringBuilder.append(StringEscapeUtils.escapeEcmaScript(e.getData()));
stringBuilder.append("');");
webView.loadUrl(stringBuilder.toString());
StringEscapeUtils.escapeEcmaScript solves the problem, add this library to your gradle:
compile 'org.apache.commons:commons-lang3:3.4'

JSON error in console: Unexpected token :

Here is my json http://jsbin.com/wagomomuda/1/edit
when I try to run, I get an error as unexpected token :, i tried validating my json, in many sites, it says its valid.Can anyone please help me out with this, as I am new to json.
Check the bellow json
var jsonvarable='{"content":{"comments":[{"userName":"ElizabethEstes","currentDate":"-09/10/2014","currentTime":",08:42AM","image":"ellizabeth_estes.png","data":"Cumsociisnatoquepenatibusetmagnisdisparturientmontes,nasceturridiculusmus.Vivamussagittislacusvelauguelaoreetrutrun"},{"userName":"BillBaggins","currentDate":"-09/10/2014","currentTime":",08:42AM","image":"john-smith_img.png","data":"Cumsociisnatoquepenatibusetmagnisdisparturientmontes,nasceturridiculusmus.Vivamussagittislacusvelauguelaoreetrutrun"},{"userName":"SarahSmith","currentDate":"-09/10/2014","currentTime":",08:42AM","image":"sarah.png","data":"Cumsociisnatoquepenatibusetmagnisdisparturientmontes,nasceturridiculusmus.Vivamussagittislacusvelauguelaoreetrutrun"}]}}';
your json is valid,but your script is invalid, code between { } is a code block,so your code looks like
"content":{ ......}
add this is a invalid script
you may change it to
var myJson = {"content":{ ......}};

Issue With JSON Data

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.

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