The line of code below, which I thought creates a javascript object, gives me the following error:
Uncaught SyntaxError: Unexpected token {
This is the line of code:
var flyer2 = {"id":20,"img_url":"http://images.awfbeat.com/48395b02-59e5-4e26-b7bc-8c603008c9c4","img_width":0,"img_height":0,"popularity":0,"color":"#67c547","tag":"Jul 10","category":"festivals","title":"Darth Vader\\\u0027s \\\"Annihilator\\\"","title_slug":"darth-vader-s-annihilator-","performer":"","performer_sort":"xxxx","posted":"2012-03-11 04:09:20.0","facebook_event_id":"","venue_postal":"90802","venue_name":" Aquarium of the Pacific","venue_street":"100 Aquarium Way","venue_city":"Los Angeles","venue_region_abbr":"CA","venue_lat":"33.762226","venue_lng":"-118.19686","needs_info":false};
What exactly am I doing wrong?
You're html-encoding the quotes.
Not 100% sure, but I guess the ampersand is parsed as the bitwise and operator, semicolons as line end symbols.
If this is serverside code then
the solution is:
var flyer2 = "{"\""id"\"":20,"\""img_url"\"":"\""http://images.awfbeat.com/48395b02-59e5-4e26-b7bc-8c603008c9c4"\"","\""img_width"\"":0,"\""img_height"\"":0,"\""popularity"\"":0,"\""color"\"":"\""#67c547"\"","\""tag"\"":"\""Jul 10"\"","\""category"\"":"\""festivals"\"","\""title"\"":"\""Darth Vader\\\u0027s \\\"\""Annihilator\\\"\"""\"","\""title_slug"\"":"\""darth-vader-s-annihilator-"\"","\""performer"\"":"\"""\"","\""performer_sort"\"":"\""xxxx"\"","\""posted"\"":"\""2012-03-11 04:09:20.0"\"","\""facebook_event_id"\"":"\"""\"","\""venue_postal"\"":"\""90802"\"","\""venue_name"\"":"\"" Aquarium of the Pacific"\"","\""venue_street"\"":"\""100 Aquarium Way"\"","\""venue_city"\"":"\""Los Angeles"\"","\""venue_region_abbr"\"":"\""CA"\"","\""venue_lat"\"":"\""33.762226"\"","\""venue_lng"\"":"\""-118.19686"\"","\""needs_info"\"":false}";
else
var flyer2 = {"id":20,"img_url":"http://images.awfbeat.com/48395b02-59e5-4e26-b7bc-8c603008c9c4","img_width":0,"img_height":0,"popularity":0,"color":"#67c547","tag":"Jul 10","category":"festivals","title":"Darth Vader\\\u0027s \\\"Annihilator\\\"","title_slug":"darth-vader-s-annihilator-","performer":"","performer_sort":"xxxx","posted":"2012-03-11 04:09:20.0","facebook_event_id":"","venue_postal":"90802","venue_name":" Aquarium of the Pacific","venue_street":"100 Aquarium Way","venue_city":"Los Angeles","venue_region_abbr":"CA","venue_lat":"33.762226","venue_lng":"-118.19686","needs_info":false};
or else use single quota.
Related
I am trying to catch invalid operators passed to eval() function so that it can display invalid expression on screen but it's not working. Is there something I am missing? sorry if this sounds silly but I am beginner to JavaScript.
function evaluating(el){
var invalidOperators = ['//','**','+/','/+','+*','*+','-/','/-','-*','/*','*/'];
var i;
for(i=0;i<invalidOperators.length;i++){
if(el.search(invalidOperators[i])!= -1){
document.getElementById('display').value = 'INVALID SYNTAX';
}
else{
document.getElementById('display').value = eval(el);
}
}
}
I tried adding \ to all strings in invalidOperators as for special characters of regex but it's still not working.
If you don't break the loop with break;, an invalid string can be found, but immediately after that, the next invalid string isn't found, so in the end you don't get the INVALID SYNTAX you're expecting, and that's a false negative.
I would simplify the function and write something like below. Your function should only do one thing, that is, return true or false (depending whether the string is valid or not). Then, use this function inside another function that does only one thing, that is, write 'INVALID SYNTAX' in a div. The smaller and more specialized a function, the better.
const invalidOperators = ['//','**','+/','/+','+*','*+','-/','/-','-*','/*','*/'];
// returns true if the string to test contains any of the elements in the invalidOperators array
const isInvalid = toTest => invalidOperators.some( e => toTest.includes(e) );
const checkInvalid = event => output.innerHTML = isInvalid(event.target.value) ? "INVALID!!" : "Okay.";
<input onkeyup="checkInvalid(event)"/>
<div id="output"></div>
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-)
Hi there I am trying to figure out what is going wrong. I am getting the error
Uncaught SyntaxError: Unexpected end of input in line 1
which is
var itemList = new Array();
A snippet of the code is included
var itemList = new Array();
$( document ).ready(function(){
var $newItem = $('#newItem');
var $itemList =$('#itemList');
var itemTouchStart;
var itemTouchEnd;
var itemTouchStartX;
var itemTouchEndX;
if( window.localStorage) //when application starts check if there is data
{
itemList = JSON.parse(window.localStorage.getItem('itemList'));
}
if(null !== itemList)
{
for (i=0;i<itemList.length; i++)
{
var itemNew = '<li data-key="'+ itemList[i].key +'"><span>'
+itemList[i].item +'</span></li>';
$itemList.append(itemNew);
}
}
else
{
itemList = new Array();
}
The line number of the error is wrong. The problem is at the end, you never close the function you're passing into ready or the call to it. Add }); at the end.
If that's missing only because you quoted a
...snippet of the beginning of the code...
...then the answer is that there's nothing wrong with line 1 that's apparent from your question. Weird errors like that can sometimes be down to invisible characters in the source, but I would expect to see an illegal character error rather than unexpected end of input. Unexpected end of input is pretty much what it says: You have a control structure of some kind open and haven't closed it when the parser reaches the end of the code text.
I find the Meteor JavaScript parser page is quite handy for diagnosing syntax errors.
I have the following JSON: http://pastebin.com/Sh20StJY
SO removed the chars on my post, so look at the link for the real JSON
which was generated using JSON.stringify and saved on Firefox prefs (pref.setCharPref(prefName, value);)
The problem is that when I save the value, Firefox does something that corrupts the JSON. If I try a JSON.parse retrieving the value from the config I get an error:
Error: JSON.parse: bad control character in string literal
If I try to validate the above JSON (which was retrieved from the settings) I get an error at line 20, the tokens value contains two invalid characters.
If I try a JSON.parse immediately after JSON.stringify the error doesn't occur.
Do I have to set something to save in a different encoding? How can I fix it?
nsIPrefBranch.getCharPref() only works for ASCII data, your JSON data contains some non-ASCII characters however. You can store Unicode data in preferences, it is merely a little bit more complicated:
var str = Components.classes["#mozilla.org/supports-string;1"]
.createInstance(Components.interfaces.nsISupportsString);
str.data = value;
pref.setComplexValue(prefName, Components.interfaces.nsISupportsString, str);
And to read that preference:
var str = pref.getComplexValue(prefName, Components.interfaces.nsISupportsString);
var value = str.data;
For reference: Documentation
Your JSON appears to contain non-ASCII characters such as ½. Can you check what encoding everything is being handled in?
nsIPrefBranch.setCharPref() assumes that its input is UTF-8 encoded, and the return value of nsIPrefBranch.getCharPref() is always an UTF-8 string. If your input is a bytestring or a character in some other encoding, you will either need to switch to UTF-8, or encode and decode it yourself when interacting with preferences.
I did this in one place to fix this issue:
(function overrideJsonParse() {
if (!window.JSON || !window.JSON.parse) {
window.setTimeout(overrideJsonParse, 1);
return; //this code has executed before JSON2.js, try again in a moment
}
var oldParse = window.JSON.parse;
window.JSON.parse = function (s) {
var b = "", i, l = s.length, c;
for (i = 0; i < l; ++i) {
c = s[i];
if (c.charCodeAt(0) >= 32) { b += c; }
}
return oldParse(b);
};
}());
This works in IE8 (using json2 or whatever), IE9, Firefox and Chrome.
The code seems correct. Try use single quotes '..': '...' instead of double quotes "..":"..." .
I still couldn't find the solution, but I found a workaround:
var b = "";
[].forEach.call("{ JSON STRING }", function(c, i) {
if (c.charCodeAt(0) >= 32)
b += c;
});
Now b is the new JSON, and might work...
I run next code and I miss somthing, for me it seem OK :
window.onload = TitleFieldInit;
function TitleFieldInit() {
var str = document.cookie.split("=")[1];
var space = str.split("=")[1];
space = space.split(";")[0];
alert(space);
// while( space.indexOf('%20' )+1) space = space.replace(/%20/,' ');
if (document.cookie != "") {
document.getElementById("TitleField").innerHTML = "Your Title is : " + space;
}
}
and I got err in FireFox rror"space is undefined" why ?
In chrome "Uncaught TypeError:Cannot call method'split' of Undefined"
Thx for helping.
This code will never work for any input.
str is a already part of result of split by =, i.e. it contains no = symbols.
Then you split that result again by =, which of course will return you one-element array and str.split("=")[1] will always be undefined.
Looks like you're trying to read cookie value... but second .split("=") is not needed at all.
Ah, and you got different results in different browsers, cause they contain different data in their cookies.
PS: Instead of while( space.indexOf('%20' )+1) space = space.replace(/%20/,' '); you may write space = space.replace(/%20/g,' '); to replace all of them at once.