I'm trying out localStorage and JSON using a variety of browsers with this piece of code:
function getStorage() {
stored = JSON.parse(localStorage['test']);
if (typeof stored == 'object') {return stored;}
}
Chrome gives me the following error message: "Uncaught SyntaxError: Unexpected token u" for the first line inside the function body. For that same line, Safari says "SyntaxError: Unable to parse JSON string". Firefox does not give any error messages for that line.
Other JSON.parse examples (from books, etc) work fine in both Safari and Chrome. For instance, this one from "Pro JavaScript" by Nicholas Zakas:
var jsonText = "{\"name\":\"Nicholas C. Zakas\", \"age\":29, \"author\":true }";
var object = JSON.parse(jsonText);
alert(object.name); //"Nicholas C. Zakas"
No problem at all with getting that to work. Local storage also works fine in both.
I've also checked the encoding on all my files using file -I my file and all files, both my own and the ones from the above book, are encoded as filename.html: text/html; charset=us-ascii - so encoding doesn't seem to be the problem here.
This is perplexing. Thanks a lot for any help.
/ James
It's because the content of localStorage['test'] is undefined, hence the unexpected u.
Thanks for the advice on debugging the contents of localStorage directly. The bug was in the line if (localStorage.length == 0). I had some other data in localStorage from previous apps, so json didn't get set to anything inside that conditional.
Related
I have a Laravel application with Vue js and until a while ago it was working perfectly. Now when I go to any page that uses Vue js this error appears: [Vue warn]: Error in render: "SyntaxError: Unexpected token u in JSON at position 0".
When I reload the page by clearing the cache (Control + Shift + R on Mac OS) it works again, but when I update without this command the error appears again.
PS: I didn't do any package updates for both laravel and npm, it just stopped working out of nowhere.
Try this in the console:
JSON.parse(undefined)
Here is what you will get:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at <anonymous>:1:6
In other words, your app is attempting to parse undefined, which is not valid JSON.
There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).
window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn) // oops, misspelled!
The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.
Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.
Sometime it is becaseu of this let data = JSON.parse(this.response); so try to change it to
let data = JSON.parse(this.responseText);
I really did was change this.response to this.responseText
I posted a question on this yesterday to the GitHub support page and it got flagged as a duplicate - the original answer is here. This issue doesn't automatically fix like it did for that user. Instead, it seems to come and go with no pattern, so I don't have a good way to replicate it. Some songs will work at one point in time, then they won't a couple minutes later.
Error:
[debug] Encodings: locale cp1252, fs utf-8, out UTF-8, pref cp1252
[debug] youtube-dl version 2020.09.20
[debug] Python version 3.7.8 (CPython) - Windows-10-10.0.19041-SP0
[youtube:search] query "iron man 3 song": Downloading page 1
[debug] exe versions: none
[debug] Proxy map: {}
ERROR: query "song name": Failed to parse JSON caused by JSONDecodeError('Expecting value: line 1 column 1 (char 0)')); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.
I get the issue when attempting to extract the data from the video. Here is a snippet of the code I am using:
ydlOps = {
'format': 'bestaudio/best',
'outtmpl': './%(title)s.webm',
'noplaylist': True,
'extractaudio': True,
'audioformat': 'webm',
'default_search': 'ytsearch1',
'quite': True,
'verbose':True,
'version': True
}
with youtube_dl.YoutubeDL(ydlOps) as downloader:
songData = downloader.extract_info(url, download=download)
I have changed the options, tried other options said to have worked, and nothing seems to make a difference. Some will work, then not, then they will again.
I think this is a youtube-dl bug. I wrote a parser for youtube searches and it also broke.
When looking previously at the response from youtube, all the JSON data was stored like this:
window["ytInitialData"] = {...}
So you just had to search through the server's response for the string 'window["ytInitialData"]' to find the relevant JSON and extract it. But now, youtube stores the JSON like this inside the html file sent by the server
var ytInitialData = {...}
This needs to be changed on youtube-dl's part when parsing the results.
What's strange is that sometimes youtube uses the previous version and sometimes it uses the current one. I think it's because the change in javascript is progressively being rolled out accross all youtube servers.
Also note that now, the line containing all the JSON ends with '; ' instead of just ';'. This might also require a change from youtube-dl.
You need to submit a pull request to youtube-dl or wait for somebody to fix it.
Anytime that I use serializeJSON in cf9 the JSON it returns is prepended with '//'. This is pretty frustrating because even coldfusion will throw an error trying to decode that as json. For example:
var a = { stuff = 'some content' };
a = serializejSON( a ); // the content of a is now: //{"STUFF":"some content"}
b = deserializeJSON( a );
The above code will throw an error saying something like 'unable to parse character at position 1: /'. In order to make this work I have to do a string replace and swap out '' for the '//'.
I can't seem to find any information on this issue. Is this some sort of feature that I don't understand and is working as intended? Am I missing some sort of setting that fixes this?
You can disable this in the ColdFusion administrator. Go to Server Settings > Settings and uncheck Prefix serialized JSON with
There are, however, security implications if you turn this off. This helps protect your JSON data from cross-site scripting attacks and is explained more in depth in this StackOverflow answer
Quick update: A guy previously submitted a bug ticket to Adobe to disable the secure JSON prefix of the SerializeJSON function in the form of an attribute..
Ticket [Fixed]
Since then Adobe obliged and added the attribute useSecureJSONPrefix onto the SerializeJSON funtion.
Documentation
That way you can keep the secure setting in ColdFusion Administrator and simply disabled it where you don't need it.
I tried different approaches so far including fromJSON(readLines(url),unexpected.escape="keep")
and fromJSON(getURL(url),unexpected.escape="keep").
The thing I stumbled upon now is that if my request looks as follows:
url = "https://api.instagram.com/v1/users/142121981/?client_id=****************************"
(fill in your clientid) combined with readLines(), which has worked better for me so far, I recieve the error:
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") : cannot open: HTTP status was '400 BAD REQUEST'
If you open this URL in your browser u still get a JSON atring:
{"meta":{"error_type":"APINotFoundError","code":400,"error_message":"this user does not exist"}}
Telling me, that a user with this ID doesnt exist.
What I want is a alternative to readLines() that still reads in this JSON string instead of throwing an error.
Hope this is explanation enough! If not ask me anything you need to know!
Thanks to the tips by MrFlick I dived into the httrpackage.
The solution for me (or best practice) is to use
response = fromJSON(rawToChar(GET(url)))
This gives back an R object even if the user doesnt exist.
I use RCurl, httr & RJSONIO packages and:
fromJSON(getURL()))
I'm using v3.9 UI with jQuery wrapper:
Now that I've solved my 'Maximum Request Length Exceeded' error within IE9 (from here:
FineUploader Error Handling
). All my FineUploader code is within this other link, and didn't think I needed to post it again.
I'm now looking for a better way to let IE users know when they've attempted to upload a file that's too large (Chrome, FF users get the too large file alert, so this isn't a problem). I don't think I need to mess with the 'messages' option as these are working as they should for all the other browsers. It's IE that's not working as it should! IE users will get all the way up to the server with the file they've selected. For handling uploading a file that exceeds the fileSize property, I have code on my server side to checks content length > 'n' and if so then return JSON success = false. See below:
[HttpPost]
public JsonResult UploadFile(HttpPostedFileWrapper qqfile, int surveyInstanceId, int surveyItemResultId, int itemId, int loopingIndex)
{
bool isValid = false;
// file is too big, throw error.
if (qqfile.ContentLength > (1024*1024*2.5))
{
return CreateJsonResult(false);
}
More Code here if the file is 'good'
}
private JsonResult CreateJsonResult(bool isSuccess)
{
var json = new JsonResult();
json.ContentType = "text/plain";
json.Data = new { success = isSuccess };
return json;
}
This short circuits an invalid file upload based on size. Great, but can I return more than just success=false and have this additional JSON value used by FineUploader to display a more useful message to the user? Currently all that shows is 'Upload Failed'. How do I reference the specific html element for that invalid file, so I can add a more descriptive error?
Also, I do have the .on('error') method, but I'm not sure how to trigger this. This would be a logic place to look, as the file upload size issue IS an error. Help? Thanks.
Using the Content-Length of the request to enforce file size restrictions is not a good idea. All upload requests sent by Fine Uploader, by default, are multipart encoded. The Content-Length for multipart encoded requests is the size of the ENTIRE request, not just the file.
In a comment to your answer for your last question, I pointed to a specific section of the documentation that allows you to control the failure text that appears next to a file in Fine Uploader UI mode. All you have to do is set the mode property of the failedUploadTextDisplay option to "custom". Server-side, return the error message text you would like to appear next to the failed file in an "error" property of your JSON response. See the bottom of the "handling errors" documentation section for more details.
UPDATE
It looks like you are using the ContentLength property of the HttpPostedFileWrapper which returns the size of the uploaded file. This was a bit confusing for me at first, since Content Length generally refers to the size of a request. The name choice for this property was a poor one on Microsoft's part, IMHO. So, you can disregard #1 in my answer.