parsing a JSON fails with missing element in javascript - javascript

I am trying to use Youtube's Gdata JSON response in javascript. My code iterates through the playlist and extract the item data.but for few videos the rating is not there which throws
"TypeError: item.gd$rating is undefined"
is there a way to check before accessing the element.
this is the code with with i fetch the json response.
var avgrating = item['gd$rating']['average'];
var maxrating = item['gd$rating']['max'];
var minrating = item['gd$rating']['min'];
var numRaters = item['gd$rating']['numRaters'];

One way you can just do to avoid error is
var rating = item['gd$rating'] || {}; // If it is undefined default it to empty object
var avgrating = rating['average']; //now if it is not present it will just give undefoned as value
var maxrating = irating['max'];
var minrating = rating['min'];
var numRaters = rating['numRaters'];
Or explicitly check:
var rating = item['gd$rating'], avgrating, maxrating;
if(rating)
{
avgrating = rating['average'];
maxrating =rating['max'];
...
}
Note that in the if condition we are checking for truthiness of the expression so, anything other than undefined, null, "", false, 0 will be treated as true and will go into the condition. But here you are sure that it will be either an object or nothing so you can rely on this check.

Related

Javascript object undefined issue

I'm a little stumped here. Can someone tell me why this works:
var selectedAttrs = {"mattress_size_variation":{"displayName":"Mattress Size","value":"King","displayValue":"King"},"mattress_feel_variation":{"displayName":"Mattress Feel","value":"Soft","displayValue":"Soft"}};
var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();
//Returns "King"
But this does not and throws an error?
var selectedAttrs = {"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}};
var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();
TypeError: Cannot read property "value" from undefined
What is the difference and how should I get the value from the last one? I'm assuming I need to do some sort of check since one works and the other does not.
There's a untrimmed space in your second JSON so you have to access that property using square brackets:
selectedAttributes['mattress_size_variation ']
var selectedAttrs = '{"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}}'
var selectedAttributes = JSON.parse(selectedAttrs);
console.log(selectedAttributes['mattress_size_variation '].value);

ValueIterator.toArray().indexOf() returns unexpected results?

UPDATE: this is NOT a question on javascript alone, but related to the javascript implementation on the MarkLogic platform.
As the title of this question points out it is about the specific behaviour of the ValueIterator that is returned by the xdmp.userRoles() function.
I am trying to see if a user has a certain role in MarkLogic Security database, therefor I have done this :
declareUpdate();
var pid = '7610802';
// TODO validate that user can do this
var spo = 'scc-proj-' + pid + '-owner';
var spm = 'scc-proj-' + pid + '-member';
var spam = 'scc-proj-' + pid + '-adv-member';
// we need the security db Ids of these roles
var spoId = xdmp.role(spo);
var spamId = xdmp.role(spam);
var acceptedRoleIds = [spamId,spoId];
// get roleIds from sec db for this user
var userRoleIds = xdmp.userRoles('scc-user-1');
// map ValueIterator to array
var userRoleIdsArray = userRoleIds.toArray();
Now the userRoleIdsArray holds ids as unnsigned long like this:
[
"1088529792688125909",
"1452323661308702627",
"10258509559147330558",
"10161853410412530308",
"6677433310138437512",
"12773061729023600875",
"7482704131174481508",
"3191093315651213021", <<<<< this is the one!!!
"5126952842460325403",
"7089338530631756591",
"15520654661378671735",
"13041542794130379697"
]
Now indexOf() gives me -1 aka not found
userRoleIdsArray.indexOf(3191093315651213021);
OR
userRoleIdsArray.indexOf("3191093315651213021");
Gives :
-1
While
userRoleIdsArray[7]==3191093315651213021;
Gives :
true
What am I missing here? Is this not the way to use indexOf() ?
UPDATE >>> Stuff below was 'on-the-side' but turns out to be distracting from the above core question. The behaviour below is answered by #DaveCassel's comment.
btw on the created array acceptedRoleIds it is even more strange:
acceptedRoleIds.indexOf(spoId);
works
acceptedRoleIds.indexOf(3191093315651213021);
does not?
Could this large number error in javascript be relevant?
You want to find a String, not a number. Use: userRoleIdsArray.indexOf("3191093315651213021");
This works:
var array = [
"1088529792688125909",
"1452323661308702627",
"10258509559147330558",
"10161853410412530308",
"6677433310138437512",
"12773061729023600875",
"7482704131174481508",
"3191093315651213021",
"5126952842460325403",
"7089338530631756591",
"15520654661378671735",
"13041542794130379697"
];
var n = array.indexOf("13041542794130379697");
document.write(n);
output: 11
The mismatch is that ValueIterator.toArray() returns an array of Values (Value[]). When you call .indexOf, you're passing in a string or an unsignedLong rather than a value. Because the types don't match, .indexOf() doesn't report a match.
You can solve the problem by iterating through the loop. Note that I use the '==' operator rather than '==='; the type conversion is needed.
// get roleIds from sec db for this user
var userRoleIds = xdmp.userRoles('my-user');
// map ValueIterator to array
var userRoleIdsArray = userRoleIds.toArray();
var target = 15520654661378671735;
var index = -1;
for (var i in userRoleIdsArray) {
if (userRoleIdsArray[i] == target) {
index = i;
}
}
index

Json Javascript String Syntax error when parsing an array

I have the following code javascript code
var tasksPlayed = [];
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);
this gives an error
SyntaxError: JSON.parse
Im not sure why, if I do a .toSource() on the objects I get
keyValue:"[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true]"})
Any ideas where I might be going wrong
I don't get this error when I run the code, but the thing with the null values is that tasksPlayed is an array, so when you set tasksPlayed[90] = true;, then it automatically fills all positions from 0 to 89 with null. Try using a plain object instead of an array:
var tasksPlayed = {};
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);

Cannot Read Property Javascript

Cannot grab the follower count from the following URL. Shows up as blank. Am I grabbing the right parameters?
https://developer.foursquare.com/docs/explore#req=pages/search%3Fname%3DNintendo
function foursquareFriends(url) {
var responses = UrlFetchApp.fetch(url);
var json = responses.getContentText();
var data = JSON.parse(json);
var likes = data.response.results.followers.count;
return likes;
}
You should do this (using this)
data.response.results[0].followers.count;
(And of course if you have more than 1 value - you should iterate).

How to stock array with localStorage (Chrome Extension)?

I tried to stock an array in localStorage but then I read it was impossible. So I tried that:
array = {};
array.name = $('[name="name"]').val();
array.username = $('[name="username"]').val();
array.password = $('[name="password"]').val();
alert(localStorage['accounts']);
local = JSON.parse(localStorage['accounts']);
localu = local.push(array);
alert(JSON.stringify(localu));
In fact the scripts stops at the first alert which returns '[]' (I previously put that value to check the result).
Why isn't my script working?
JavaScript, {} is an Object. [] is an Array.
var array = [] and var array = new Array() do the same thing.
An array is an ordered container of stuff, each value has an index not a key.
An object is a named container of stuff, each "stuff" has a key.
Your array is definitely an object.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
alert(localStorage['accounts']);
// > undefined OR the value
local = JSON.parse(localStorage['accounts']);
// local contains a parsed version of localStorage['accounts']
localu = local.push(array);
// localu = 0 (push returns the length i think?)
alert(JSON.stringify(localu));
Try the following. I've not tested it, but might work.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
if (localStorage['accounts'] == undefined) { // fixed
// does the key exist? No so create something to get us started
localu = { accounts: [] };
} else {
// the key exists! lets parse it
localu = JSON.parse(localStorage['accounts']);
}
// add the new "data" to the list
localu.accounts.push(data);
// save the results (we have to stringify it)
localStorage['accounts'] = JSON.stringify(localu);

Categories

Resources