JSON key exists but returns false - javascript

First of all, all my code is done in node.js but this can all be applied to javascript too.
This is my code I use to check if the keys exist, the problem is that it always returns false. So I added in the console.log to shows what the values are:
if(!choice.name || !choice.realm || !choice.region || !choice.roll){
console.log(choice);
console.log(choice.name);
console.log(choice.realm);
console.log(choice.region);
console.log(choice.roll);
return false;
}
This is the output of that:
{"name":"Imacactus","realm":"Velen","region":"US","roll":"DPS"}
undefined
undefined
undefined
undefined
I'm guessing it has something to do with the quotes? but I've never heard of quotes messing it up. Is this a node.js problem? I've also tried .hasOwnProperty('realm') and it still failed.
This is most of the code with all the functions: http://pastebin.com/DUN9VdHr

You need to parse your json into a javascript object before you can reference its properties.
You can use JSON.parse
var choiceobj = JSON.parse(choice);
if(!choiceobj.name || !choiceobj.realm || !choiceobj.region || !choiceobj.roll){
console.log(choiceobj);
console.log(choiceobj.name);
console.log(choicepbj.realm);
console.log(choiceobj.region);
console.log(choiceobj.roll);
return false;
}

The problem is that the quotes is part of the key so to access it you have to do something like:
console.log(choice['"name"']);

Related

Why JavaScript null check doesn't working?

function readProperty(property)
{
console.log(localStorage[property]) //Alerts “null”
if(localStorage[property] == null)
{
console.log('Null chek')
return false;
}
return localStorage[property];
}
log outputs "null", but 'if()' doesn't work. I try with ===, its not work too. Help please.
UPD: Thanks everyone this change helped me if(localStorage[property] == 'null')
The keys and the values stored with localStorage are always in the
UTF-16 string format, which uses two bytes per character. As with
objects, integer keys are automatically converted to strings.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Try:
localStorage[property] === 'null'
Although: console.log(localStorage[property]) may report null, the actual value is undefined.
So, in your if statement, if you test against undefined, you'll get a match.
Better yet though, just test for the existence or non existence of a value with:
if(localStorage[property])... // Tests for any "truthy" value
or
if(!localStorage[property])... // Tests for any "falsey" value
Well, I don't know if you're trying to use the global localStorage or if it's a defined variable in your code.
If you're using the localStorage API, you should check if a key exists like this...
if (!localStorage.getItem("my-item")) {
console.log("item doesn't exist.");
}
The .getItem() method returns null when the key isn't defined so checking using ! or item !== null work.
.getItem() reference from MDN, https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem.
you have to get item from localStorage using getItem() function like that
if(!localStorage.getItem(property) || localStorage.getItem(property)===null){
// there is no item in localStorage with the property name
}

Is .concat() method used wrongly here?

So, I have two ajax calls, which are chained in a promise.
For example
promiseData.then(res1, res2) {
let responseOneParsed = JSON.parse(res1)
let responseTwoParsed = JSON.parse(res2)
}
I am concatenating these two, like this
concatenatedArr = responseOneParsed.data.concat(responseTwoParse.data)
So, this is clear.
But, sometimes one of these two ajax calls returns undefined, since the response is empty (should be), and I get the error:
error TypeError: Cannot read property 'concat' of undefined
Which is again very clear, but how can I scale this code to accept one of these parameters, if other is undefined, so it does not fail? Is .concat() used wrongly here?
You can easily make it with || operator and empty array: []
like this
concatenatedArr = (responseOneParsed.data || []).concat(responseTwoParse.data || [])
Isn't this just a case of proper sanity checking?
Check to see if responseOneParsed.data is valid, if it is, call concat, else, apply the second data.
concatenatedArr = responseOneParsed.data ?
responseOneParsed.data.concat(responseTwoParse.data ? responseTwoParse.data: [] )
:responseTwoParse.data

How to check if an object has a specific key without try/catch

I am receiving this JSON from server, and I need to check if it contains the key read.nores
if I do it like this
if (data[0]["read.nores"]) {
return;
}
it will crash because it does not contain that key.
How can I check if the key is there without a try/catch method, something like .has("read.nores")?
Reading an undefined key safely produces undefined, but reading a key from undefined will throw, so the problem will be specifically that data[0] doesn't exist, not that data[0]["read.nores"] doesn't exist.
To check for that, change it to:
if (data[0] && data[0]["read.nores"]) {
return;
}
It won't crash.
If you check any property of an object and it is not defined in the object it is by default undefined. So your if condition will work perfectly.

JSON.stringify(undefined) is not a string

JSON.stringify(null) returns the string null.
JSON.stringify(undefined) returns the value undefined. Shouldn't it return the string undefined?
Parsing the value undefined or the string undefined gives a SyntaxError.
Could someone explain why JSON chokes on undefined and how to get around it when stringifying / parsing values?
undefined is not valid JSON, so the function is working properly.
http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example
if(JSON.stringify(input) === undefined) {
// error handle
}
or
if(input === undefined) {
// error handle
}
else {
JSON.stringify(input);
}
Sorry. Life is hard sometimes. This is pretty much what you have to do.
The reason for this is that null is caused by a variable that doesn't have a value, so when converted to JSON it gives you JSON that doesn't have a value, undefined means it doesn't exist at all, so you can't create a JSON object of something that doesn't exist. Just check
if(typeof myvar === 'undefined')
before you run it and handle the error gracefully in the code.
Generally try to avoid undefined in your JS they can to weird things all over the place, and are NOT the same as null and are usually handled differently.

javascript null comparison different on chrome and firefox

I have the following code:
var a=sessionStorage.getItem("Token");
alert(a==null);
The returned value is null (If I alert(a) it displays null). The problem is that the alert(a==null) display is TRUE on firefox and FALSE on safari and chrome. WTH? I have tried a===null with the same results as well as !a.
What am I doing wrong or what am I not aware of?
Thanks for any help.
You said in a comment: "I set Token with sessionStorage.setItem("Token",null);"
I believe the problem is that you are supposed to use session storage to store strings. When you pass null to setItem() it converts it to a string "null". Then when you retrieve it with getItem() you get back this string "null" which is of course not equal to an actual null value.
You can see this behaviour here: http://jsfiddle.net/CWVww/1/
If you want to remove a previously set item then do this:
sessionStorage.removeItem("Token");
...and then calls to .getItem("Token") will return null.
I don't know why Firefox behaved differently. From the MDN page on session storage: "Keep in mind that everything you store in any of the storages described in this page is converted to string using its .toString method before being stored."
Your code worked perfectly with me (tested on Chrome). However, I suggest you to use the ! operator and also check the type of the current value:
var a = sessionStorage.getItem("Token");
if(!a && typeof a!=='string'){ //a doesn't exist
//Do something
}else{ //a does exist
//Do something
}
The operator ! will return true either when a is null or undefined.
You could try String(a) == "null". However, if the value of the Token item is set to "null" (the string "null") the code won't work as expected, so we have to add another condition:
var a = sessionStorage.getItem("Token");
if(String(a)==="null" && typeof a!=="string"){ //a doesn't exist
//Do something
}else{ //a does exist
//Do something
}
This way, the condition will return true when the "stringified" value of a is "null" and the type of the a var is not string

Categories