I'd check the constructor attribute.
e.g.
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;
function whatIsIt(object) {
if (object === null) {
return "null";
}
if (object === undefined) {
return "undefined";
}
if (object.constructor === stringConstructor) {
return "String";
}
if (object.constructor === arrayConstructor) {
return "Array";
}
if (object.constructor === objectConstructor) {
return "Object";
}
{
return "don't know";
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
for (var i=0, len = testSubjects.length; i < len; i++) {
alert(whatIsIt(testSubjects[i]));
}
Edit: Added a null check and an undefined check.
Answer from Programming Guy on Stack OverflowHi! I'm looking to dive back into Javascript after a 10+ year hiatus (learned some during college) in order to build out a basic piece of software using a WebSocket for a lighting control system. I notice that most of it can be done with Javascript, but every now and then there are JSON calls. Looking at JSON's wiki page, I notice it's an acronym "JavaScript Object Notation" so obviously has lots to do with Javascript, but apparently it's also " a language-independent data format." (whatever that means).
Any indications if I'll need to be proficient with JSON to work with the WebSocket? If so, any recommendations for resources to get started? Thank you!
Videos
I'd check the constructor attribute.
e.g.
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;
function whatIsIt(object) {
if (object === null) {
return "null";
}
if (object === undefined) {
return "undefined";
}
if (object.constructor === stringConstructor) {
return "String";
}
if (object.constructor === arrayConstructor) {
return "Array";
}
if (object.constructor === objectConstructor) {
return "Object";
}
{
return "don't know";
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
for (var i=0, len = testSubjects.length; i < len; i++) {
alert(whatIsIt(testSubjects[i]));
}
Edit: Added a null check and an undefined check.
You can use Array.isArray to check for arrays. Then typeof obj == 'string', and typeof obj == 'object'.
var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
if (Array.isArray(p)) return 'array';
else if (typeof p == 'string') return 'string';
else if (p != null && typeof p == 'object') return 'object';
else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));
's' is string
'a' is array
'o' is object
'i' is other
I'd check the constructor attribute.
e.g.
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;
function whatIsIt(object) {
if (object === null) {
return "null";
}
if (object === undefined) {
return "undefined";
}
if (object.constructor === stringConstructor) {
return "String";
}
if (object.constructor === arrayConstructor) {
return "Array";
}
if (object.constructor === objectConstructor) {
return "Object";
}
{
return "don't know";
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
for (var i=0, len = testSubjects.length; i < len; i++) {
alert(whatIsIt(testSubjects[i]));
}
Edit: Added a null check and an undefined check.
Answer from Programming Guy on Stack OverflowUse JSON.parse
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Using JSON.parse() has some drawbacks:
JSON.parse(1234)orJSON.parse(0)orJSON.parse(false)orJSON.parse(null)
all will return true.
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function testIsJson(value, expected) {
console.log(`Expected: ${expected}, Actual: ${isJson(value)}`);
}
// All of the following codes are expected to return false.
// But actually returns true.
testIsJson(1234, false);
testIsJson(0, false);
testIsJson(false, false);
testIsJson(null, false);
Code that handles false positives
So I rewrote code in this way:
function isJson(item) {
let value = typeof item !== "string" ? JSON.stringify(item) : item;
try {
value = JSON.parse(value);
} catch (e) {
return false;
}
return typeof value === "object" && value !== null;
}
Testing result:
function isJson(item) {
let value = typeof item !== "string" ? JSON.stringify(item) : item;
try {
value = JSON.parse(value);
} catch (e) {
return false;
}
return typeof value === "object" && value !== null;
}
function testIsJson(value, expected) {
console.log(`Expected: ${expected}, Actual: ${isJson(value)}`);
}
const validJson = { "foo": "bar" };
const notValidJson = '{ "foo": "bar" } invalid';
// expected: true
testIsJson(validJson, true);
// expected: false
testIsJson(1234, false);
testIsJson(0, false);
testIsJson(notValidJson, false);
testIsJson(false, false);
testIsJson(null, false);