I got the Json \"false\"
from server. I respond as bool
but it\'s Json so it\'s in browser type is String
instead of bool
To compare string and Boolean in JavaScript, let us see the following examples. It returns true:
false == "0"; //true
true == "1"; //true
false == ""; //true
The followings returns false:
false == "false"; //false
true == "true"; //false
In addition, try the following example too:
var data = true;
data === "true" //false
String(data) === "true" //true
https://www.tutorialspoint.com/How-do-I-compare-String-and-Boolean-in-JavaScript
var data = true;
data === "true" //false
String(data) === "true" //true
This works fine.
String.prototype.revalue= function(){
if(/^(true|false|null|undefined|NaN)$/i.test(this)) return eval(this);
if(parseFloat(this)+''== this) return parseFloat(this);
return this;
}
From: http://www.webdeveloper.com/forum/showthread.php?t=147389
Actually, you just need the first "if" statement from the function -- tests to find true or false in the code and the eval
s it, turning it into the boolean value
I think you need to look at how the JSON data is being generated. You can definitely have a normal JS boolean false in JSON.
{ "value1" : false, "value2" : true }
If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false. (from MDN Comparison Operators page)
Examples:
true == "true"; //false
true == "1"; //true
false == "false"; //false
false == ""; //true
false == "0"; //true
I would just explicitly check for the string "true"
.
let data = value === "true";
Otherwise you could use JSON.parse() to convert it to a native JavaScript value, but it's a lot of overhead if you know it's only the strings "true"
or "false"
you will receive.