Without JSON.parse, you cannot.
You can evaluate hello and alter its value later on in the code, which is much more real-world scenario.
hello = hello === 'null' ? null : hello
Answer from tonymke on Stack OverflowWithout JSON.parse, you cannot.
You can evaluate hello and alter its value later on in the code, which is much more real-world scenario.
hello = hello === 'null' ? null : hello
Assign null, I've just done this:
var a=1;
console.log(a);
a=null;
console.log(a);
console.log(a===null);
Results:
1
null
true
Though, null in JS is also a value.
The ECMAScript spec says as the first step for JSON.parse:
- Let
JTextbeToString(text).
Meaning it'll cast whatever argument it's given to a string, and null casts to "null", which is the valid JSON representation of null.
Note that a single such JSON primitive shouldn't be valid, a JSON string should be wrapped in an object or array. But parsers have traditionally been lax with that, partially due to it making the implementation simpler I suppose.
See the specification:
- Let JText be ToString(text).
It doesn't require that the first argument be a string, it attempts to convert it to a string.
"" + null will give you "null" which is a string containing valid JSON.
This is also in the spec:
Null: Return "null".
Well, parseFloat will return 'NaN' if it's not a number (null and undefined are NaNs) so you could try doing like this:
// push data points
$(series).find('data point').each(function(i, point) {
var floatVal = parseFloat($(point).text());
if (!isNaN(floatVal)) {
seriesOptions.data.push(floatVal);
}
});
A null check in JavaScript if just like any other C-style language:
if (thing == null)
Or
if (thing != null)
I find this works well in most cases against my own programming where I'm writing as I would in, say, C#; however I find other peoples code relies on things never having been declared or set and such and so, and, all in all, it boils down to a spaghetti of checking for null and "undefined" - yes, the literal string, really - and whatever else.
var s = '';
var num = parseInt(s) || 0;
When not used with boolean values, the logical OR || operator returns the first expression parseInt(s) if it can be evaluated to true, otherwise it returns the second expression 0. The return value of parseInt('') is NaN. NaN evaluates to false, so num ends up being set to 0.
You can also use the isNaN() function:
var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
You can parse it
JSON.parse('null') // null
JSON.parse('1') // 1
so
var val = sessionStorage.getItem('key');
val = JSON.parse(val);
Close to cast
Alternative would be:
var val = sessionStorage.getItem('key');
val = val*1 || null;
I just want something that would evaluate to false
You could use an empty string instead to mark the unset value:
sessionStorage.setItem('key','');
This way you can re-use your current check:
if (!sessionStorage.getItem('key')) {
// do something
}
That said, you mentioned you had a drop down to select values, and that's why you need such a value, but I think a solution involving deleting the item on the null value would be better. Here's a working demo, and the code used to make it:
var dd = document.getElementById('dropdown');
dd.addEventListener('change', function(){
var value = this.value;
if (value === 'null')
sessionStorage.removeItem('key');
else sessionStorage.setItem('key', value);
});
var check = document.getElementById('check');
check.addEventListener('click', function(){
this.innerHTML = 'Value: '+sessionStorage.getItem('key')+
', check: '+(!sessionStorage.getItem('key'));
});
<select id="dropdown">
<option value="null">none</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button id="check">Check value</button>
This is a simple function which involves the use of a function to evaluate the strings. This way you can remove the part of cases' "switch". Be aware that this handles also assignments to global variables, so I recommend it only if you know anytime where is the source from(don't allow users to use this function!)
var convertType = function (value){
try {
return (new Function("return " + value + ";"))();
} catch(e) {
return value;
}
};
You can see the jsfiddle here.
How about:
var convertType = function (value){
var values = {undefined: undefined, null: null, true: true, false: false}
,isNumber = !isNaN(+(value));
return isNumber && +(value) || !(value in values) && value || values[value];
};
convertType('null'); //=> null
convertType('something'); //=> "something"
convertType('57.321'); //=> 57.321
convertType('undefined'); //=> undefined
This seems faster @ jsPerf
var convertType = function (value){
var v = Number (value);
return !isNaN(v) ? v :
value === "undefined" ? undefined
: value === "null" ? null
: value === "true" ? true
: value === "false" ? false
: value
}
You should parse the String
var stringJson = '{"command":"SELECT","rowCount":1,"oid":null,"rows":[{"username":"xxxx"}],"fields":[{"name":"username","tableID":34722,"columnID":3,"dataTypeID":1043,"dataTypeSize":-1,"dataTypeModifier":204,"format":"text"}],"_parsers":[null]}';
var ParsedJSONResponse = $.parseJSON(stringJson);
You just have a Json (JSONResponseFromServerSide) and no reason to parse it.
Parsing the Json object returns null.
$.parseJSON({}); // returns `null`
Your code is correct check out this JSFiddle.
var JSONResponseFromServerSide = '{"command":"SELECT","rowCount":1,"oid":null,"rows":[{"username":"xxxx"}],"fields":[{"name":"username","tableID":34722,"columnID":3,"dataTypeID":1043,"dataTypeSize":-1,"dataTypeModifier":204,"format":"text"}],"_parsers":[null]}'; //it's your json string
$.parseJSON(JSONResponseFromServerSide); //nothing wrong
If JSONResponseFromServerSide is already a JavaScript object, than you don't have to do parseJSON
There's no isEmpty() method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test is undefined or null.
Ignoring whitespace strings, you could use this to check for null, empty and undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
It is concise and it works for undefined properties, although it's not the most readable.