JSON.parse error Javascript - javascript

A problem. Again. Here is the code:
if(localStorage.getItem("temporaryArray")){
var temporaryArray = JSON.parse(localStorage.getItem("temporaryArray"));
}else{
var temporaryArray = [];
}
So basically what it does is that when a new page is loaded I don't want to reset the array because later in the code I assign something to this array in localStorage. So what I'm trying to say is that if you can get this item, then when the code is loaded again assign this variable to the localStorage item. Else, just set it to an empty array. But here is the error I'm getting because the array is currently empty(I think that's the reason why):
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at main.js:61
Any help would be very much appreciated.

If a method invocation fails, it usually helps to look at what the input to the function is. I would recommend doing console.log(localStorage.getItem("temporaryArray")) before the JSON.parse() call to see what the problem is.
What I would guess the source of the problem is, is that at some point you are calling localStorage.setItem("temporaryArray",value) and have forgotten to do JSON.stringify() on the value.

Related

WHY do I get an empty object when searching by element or xpath _____ HTMLSession, requests-html

I just want to verify the element exists somehow. Trying to print it so I can compare against a string or something.
Here is the problematic code.
session = HTMLSession()
r = session.get('https://www.walmart.com/ip/Sony-PlayStation-5-Video-Game-Console/994712501')
r.html.render(timeout=20)# this call executes the js in the page
oos=r.html.xpath('/html/body/div[1]/div[1]/div/div[2]/div/div[1]/div[1]/div[1]/div/div/div/div/div[3]/div[5]/div/div[3]/div/div[2]/div[1]/section/div[2]/div/div/div/div/div')
print(oos)
#print returns []
I try to print(oos.text) and I get a callback error
#'list' object has no attribute 'text'
also tried print(oos.full_text) same error
'list' object has no attribute 'full_text'
Seems like its a list? So I tried to iterate through it.
for i in oos:
print(i)
#Prints absolutely nothing!
Pretty sure the element doesn't exist. Based on an examination of print(html) I believe I am being redirected to a capthcha page.
Therefore I am going to assume that the [] is essentially an empty list and all code is more or less doing what it's supposed to.

How to fix Cannot read property hasOwnProperty of undefined

How to fix Cannot read property 'hasOwnProperty' of undefined?
Using Angular.JS 1.3
Assigning response data in $rootScope.settings in parentConroller.
so the rootScope will be like this
$rootScope.settings = api.data;
//sample
$rootScope.settings:{
"lastLogin":"2005-01-01",
"isStudent": true,
"assignedCourse": "['JAVA + DS']"
}
And accessing the $rootScope data in anotherController.JS. But here I don't want my array inside string, so to remove double quotes, I tried below ways
Attempt 1:
if($rootScope.settings.hasOwnProperty('assignedCourse')) {
$rootScope.settings.assignedCourse = ['JAVA + DS']
}
Attempt 2:
$rootScope.settings.assignedCourse = JSON.parse(rootScope.settings.assignedCourse.replace(/'/g, '"'));
// giving me Error: Unexpected token ' in JSON at position 1
Attempt 1 is working in the application, but its getting failed when i run karma debugger which is showing TypeError: Cannot read property 'hasOwnProperty' of undefined
Literally don't know how to fix this issue. Struggling to fix more than a days
I've already gone through few SO's related to my issues. but don't get any better solutions
Side Note: currently using only plain old JavaScript, not es6 or updated version.
For starters, you may want to be using angular.isDefined($rootScope.settings.assignedCourse) instead of hasOwnProperty as it is likely syntactically closer to what you are testing for (defined value instead of property ownership)
Regarding attempt 1 failing in the test, settings is undefined. You may need to re-examine your test bed and ensure your scope is being initialized as you expect.
I recreated your attempt 2 successfully, I suspect something else is going on here and may be resulting from another line.

How to get unique id from localStorage for delete button

I have been trying for getting an id from localStorage but unable to achieve it.
My localStorage inside events contains such as below.
[{"id":"ef5","title":"wan","start":"2016-05-12","end":"2016-05-13"},{"id":"ef6","title":"wana","start":"2016-05-21","end":"2016-05-22"},{"id":"ef7","title":"haha","start":"2016-05-25","end":"2016-05-26"},{"id":"ef8","title":"asdas","start":"2016-05-20","end":"2016-05-21"},{"id":"ef9","title":"sdas","start":"2016-05-19","end":"2016-05-20"}]
Now i will provide 2 coding with different method that i have tried so far. For information, i look through into this topic: localstorage: Get specific localstorage value of which contains many items
but none works for me.
I did tried coding as below:
1st method:
$("#deleteEventYes").click(function(){
var indexDel = localStorage.getItem("events");
var deleteId = calEvent.id;
var result = localStorage.getItem("events");
function getItemHrefById(json, itemId){
return $(json).filter(function(){return this.id == itemId;})[0].href;
}
var href = getItemHrefById(result, deleteId);
alert(href); });
Above code show some kind of array method (i think) where i'm using indexDel to get item from localStorage (events) while deleteId i took from calEvent.id which is the id for the event that has been clicked for to be deleted. Other than that, i think you guys know what it is. However for this method, i use result variable instead of indexDel. Thus don't mind if i getItem from localStorage 2 times
2nd method:
for (var i = 0 ; i < indexDel.length ; i += 1) {
if(deleteId == indexDel[i].id) {
return indexDel[i];
console.log(deleteId);
console.log(indexDel[i]);
}
}
return null;
Above code is using custom loop i think. The declaration of variable for indexDel is still the same with first method. I try to use the refactoring method but it seems its hard for me to understand how is it to be done. Is it because my variable placement is wrong? or is it because it is not suitable for my case?
NOTE: I want to delete an event inside eventClick function, and so far i did retrieve the id and remove the event from the calendar based on id. However my only problem now is to match the deleted event id with the id inside my localStorage and remove the item. So far getting an id from the is quite complicated for me.
UPDATED
I already done something like this but still don't work. Anyone can tell me what went wrong here? It is not giving me any error but it just do nothing. Not even delete.
https://jsfiddle.net/v35a2o07/3/
Never mind. I think i figure it out :)
It is because i forgot to setItem & stringify it after using splice.
Here i can assume splice is the same as add/remove such wrote at w3school
http://www.w3schools.com/jsref/jsref_splice.asp
"The splice() method adds/removes items to/from an array, and returns the removed item(s)."
My final code is on this fiddle given: https://jsfiddle.net/v35a2o07/4/
So the concept is:
1) First step is declare one variable that parse your localStorage key such asvar items = JSON.parse(localStorage["events"]); so that you can use it for the loop
2) Use for loop to determine the length of localStorage based on localStorage key that we parse on No. 1
3) Use if statement to check the comparison between localStorage data with our desire data such as if(items[i].id == deleteId){
4) This is OPTIONAL but important. To enable you to check the comparison is right, create one alert or console.log() and stringify it because if you don't, you will only see [object,object]. The coding such as alert(JSON.stringify(items[i])+"<<<>>>"+deleteId); Make some else statement too if you want to be sure.
5) When all the conditions are correct, then you are ready to do some action to it. For my case, i just use splice() to delete it. It is also can be used to add item. I am not sure how is it done but try to search for it to get more info.
6) After splicing it, it is safely to break and get out from the loop.
7) This is important otherwise, it will not work. Don't forget to set it back to localStorage and stringify it such as localStorage.setItem('events', JSON.stringify(items));
That's it.
I wish this would help anyone that needs it. If i have make wrong statement or wrong concept, please make correction and clarify it for anyone.
Cheers.

Json value not showing in console

below is my console output...
console.log(data);
console.log(JSON.stringify(data));
console.log(data.errorMessage);
Console shows....
{"errorMessage":"Registration Successfull"}
"{\"errorMessage\":\"Registration Successfull\"}"
undefined
How come it is undefined?I also tried data['errorMessage'] still the same output undefined how do we fix this?
Looks like you omitted some code. And your data is changed from Object to String. So try JSON.parse(data).errorMessage in your last string.
Something turned data into a string so it no longer has properties on it. This should never be seen: "{\"errorMessage\":\"CA Registration Successfull\"}". Something in your code is changing the data type on you.
I would not use JSON.parse as Vasyl suggested right away. You need to find out why it turned to string and not just turn the string back to object.

Javascript json, check all keys for undefined ('null') and set default

Firstoff I'd like to add I've been learning javascript for like only 2 days now. I'm pretty much way ahead of myself with what I'm trying to get but here goes.
I have a json array from which I get data to replace/insert in my page. The first problem I have is that if it comes across an empty ('null') key it will just stop. Will not even try to continu.
document.getElementById("id1")src=json.img1.link;
document.getElementById("id2")src=json.img2.link;
document.getElementById("id3")src=json.img3.link;
json.img2.link is empty ('null' response from json.). javascript will then not replace "id2" but it also won't replace "id3".
I'm now trying to find a solution where it will if nothing else at least set a default.
The script is not continuing executing because it comes to an error --trying to access property link of an undefined object
Try
document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';
This way your are checking for undefined (ie null) object in img2 and assigning the default value. This assumes that what is not defined (null) is the img2 object.
Actually I don't think your code should work at all, you are missing the. before the src So, try
document.getElementById("id1").src=json.img1.link;
document.getElementById("id2").src=json.img2.link;
document.getElementById("id3").src=json.img3.link;
and let us know if that doesn't solve the problem.
Btw, +points for learning JavaScript and not just straight into jQuery!

Categories

Resources