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.
Related
I'm processing some return JSON data.
Sometimes the JSON will return something I can access via
var new_insert_id = data['internal']['new_insert_id'];
But sometimes this part of the json array data will not be returned at all, and so I need to skip this variable being set.
So I've written a simple check to make sure this data exists before trying to set the variable:
if(typeof data['internal']['new_insert_id'] != 'undefined')
{
// if data['internal']['new_insert_id'] is defined, then..
var new_insert_id = data['internal']['new_insert_id'];
}
But when the JSON returns and there is no new_insert_id I am getting the following error:
Uncaught TypeError: Cannot read property 'new_insert_id' of undefined
And the line of code it points to as the culprit is the line of my if statement.
What am I missing? I thought my if statement would check if it exists or not, or do I need to do something else when working with arrays?
Besides you can firstly check for existence of data['internal'], but you can also use the pythonic way, i.e. apply try/catch block:
try {
var new_insert_id = data['internal']['new_insert_id'];
} catch (e) {}
The statement you've written checks if new_insert_id property exists in 'internal', but it doesn't check if 'internal' exists in data variable.
This should work better:
if(typeof data['internal'] != 'undefined' && typeof data['internal']['new_insert_id'] != 'undefined')
{
var new_insert_id = data['internal']['new_insert_id'];
}
the error message says, that data['internal'] is already undefined. you need to check that before:
if(typeof(data['internal']) != 'undefined' && typeof data['internal']['new_insert_id'] != 'undefined')
You need to check data['internal'] !== undefined first :)
in your test, you are testing if the property ['new_insert_id'] of data['internal'] is undefined then you have trouble accessing it because data['internal'] is undefined hence the error you get.
You have first to check if data['internal'] is undefined.
I think it because data['internal'] is undefined.
So you need check data['internal'] first.
if(data['internal'] && data['internal']['new_insert_id'])
{
// if data['internal']['new_insert_id'] is defined, then..
var new_insert_id = data['internal']['new_insert_id'];
}
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"']);
I passed in a series of JSON objects with an AJAX call. Some of the data sets include the field C and some do not. When I include the following code, it crashes. I have tried undefined and null. Both crash.
if (myJsonObjects[i].C == undefined) {
// …
}
When you say crash I presume you mean TypeError: cannot read property of undefined value
The reason it crashes is because in the line
if(myJsonObjects[i].C == undefined){
We actually have myJSONObject[i] === undefined
So really you need to check your array bounds or make sure your array is not sparse
if(myJsonObjects[i].C == undefined){
is the similar as
if(myJsonObjects[i] && myJsonObjects[i].C){
but with mine line, you check is myJsonObjects[i] and myJsonObjects[i].c are null or undefined.
The caveat being if myJsonObjects[i].c holds false, "", 0, NaN
Try this:
if (typeof myJsonObjects[i].C == 'undefined') {}
I guess you could test the waters a little before jumping right in:
if( i in myJsonObjects && myJsonObjects[i] && !( "C" in myJsonObjects[i] ) ) { }
However your original code should not crash and shouldn't throw error either if myJsonObjects[i] is defined and is not null
How about
if ('C' in myJsonObjects[i]) { do_your_magic() }
I'm checking if(response[0].title !== undefined), but I get the error:
Uncaught TypeError: Cannot read property 'title' of undefined.
response[0] is not defined, check if it is defined and then check for its property title.
if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
//Do something
}
Just check if response[0] is undefined:
if(response[0] !== undefined) { ... }
If you still need to explicitly check the title, do so after the initial check:
if(response[0] !== undefined && response[0].title !== undefined){ ... }
I had trouble with all of the other code examples above. In Chrome, this was the condition that worked for me:
typeof possiblyUndefinedVariable !== "undefined"
I will have to test that in other browsers and see how things go I suppose.
Actually you must surround it with an Try/Catch block so your code won't stop from working.
Like this:
try{
if(typeof response[0].title !== 'undefined') {
doSomething();
}
}catch(e){
console.log('responde[0].title is undefined');
}
typeof:
var foo;
if (typeof foo == "undefined"){
//do stuff
}
It'll be because response[0] itself is undefined.
Check if condition == null;
It will resolve the problem
Check if you're response[0] actually exists, the error seems to suggest it doesn't.
You must first check whether response[0] is undefined, and only if it's not, check for the rest. That means that in your case, response[0] is undefined.
I know i went here 7 months late, but I found this questions and it looks interesting. I tried this on my browser console.
try{x,true}catch(e){false}
If variable x is undefined, error is catched and it will be false, if not, it will return true. So you can use eval function to set the value to a variable
var isxdefined = eval('try{x,true}catch(e){false}')
In some of these answers there is a fundamental misunderstanding about how to use typeof.
Incorrect
if (typeof myVar === undefined) {
Correct
if (typeof myVar === 'undefined') {
The reason is that typeof returns a string. Therefore, you should be checking that it returned the string "undefined" rather than undefined (not enclosed in quotation marks), which is itself one of JavaScript's primitive types. The typeof operator will never return a value of type undefined.
Addendum
Your code might technically work if you use the incorrect comparison, but probably not for the reason you think. There is no preexisting undefined variable in JavaScript - it's not some sort of magic keyword you can compare things to. You can actually create a variable called undefined and give it any value you like.
let undefined = 42;
And here is an example of how you can use this to prove the first method is incorrect:
https://jsfiddle.net/p6zha5dm/
This code fails with an exception indicating invalid JSON:
var example = '{ "AKEY": undefined }';
jQuery.parseJSON(example);
I was able to fix it by replacing all undefineds with empty strings. Are undefineds not part of JSON?
If you can wrap your head around this, the token undefined is actually undefined.
Allow me to elaborate: even though JavaScript has a special primitive value called undefined, undefined is not a JavaScript keyword nor does it have any special meaning. You can break code which tests for the existance of an object by comparing to undefined by defining it.
var obj = { BKEY: 'I exist!' };
if (obj.AKEY == undefined) console.log ('no AKEY');
if (obj.BKEY == undefined) console.log ('should not happen');
undefined='uh oh';
if (obj.AKEY == undefined) console.log ('oops!'); // Logically, we want this to execute, but it will not!
if (obj.BKEY == undefined) console.log ('should not happen');
The only console output will be 'no AKEY'. After we've assigned to the global variable undefined, obj.AKEY == undefined becomes false because undefined != 'uh oh'. obj.BKEY == undefined still returns false, but only because we're lucky. If I had set obj.BKEY='uh oh', then obj.BKEY == undefined would be true, even though it actually exists!
You probably want to explicity set AKEY to null. (By the way, null is a keyword; null='uh oh' throws an exception).
You could also simply omit AKEY from your JSON, in which case you would find:
typeof(example.AKEY) == 'undefined'
(If you set AKEY to null, then typeof(example.AKEY) == 'object'.)
The only real difference between setting to null and omitting is whether you want the key to appear in a foreach loop.
No, but null is. RFC 4627 §2.1:
A JSON value MUST be an object, array,
number, or string, or one of the
following three literal names:
false null true
var example = '{ "AKEY": null }';
Correct. Undefined and functions are not represented in JSON. http://www.json.org/js.html
They're not permitted in JSON...look at the alternative and it's clear as to why:
var example = '{}';
var obj = jQuery.parseJSON(example);
obj.AKEY //undefined
If it's undefined, when you go to access it, it's the same as the key not even being present. Since JSON's primary purpose is for transmitting data (otherwise the broader object literal syntax is fine)...it's better to leave it out altogether.