Is there a known way or a library that already has a helper for assessing whether an object is serializable in JavaScript?
I tried the following but it doesn't cover prototype properties so it provides false positives:
_.isEqual(obj, JSON.parse(JSON.stringify(obj))
There's another lodash function that might get me closer to the truth, _.isPlainObject
. However, while _.isPlainObject(new MyClass())
returns false
, _.isPlainObject({x: new MyClass()})
returns true
, so it needs to be applied recursively.
Before I venture by myself on this, does anybody know an already reliable way for checking if JSON.parse(JSON.stringify(obj))
will actually result in the same object as obj
?
function isSerializable(obj) {
var isNestedSerializable;
function isPlain(val) {
return (typeof val === 'undefined' || typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number' || Array.isArray(val) || _.isPlainObject(val));
}
if (!isPlain(obj)) {
return false;
}
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (!isPlain(obj[property])) {
return false;
}
if (typeof obj[property] == "object") {
isNestedSerializable = isSerializable(obj[property]);
if (!isNestedSerializable) {
return false;
}
}
}
}
return true;
}
Recursively iterating over all of given object properties. They can be either:
Any other value anywhere within passed obj
will cause it to be understood as "un-serializable".
(To be honest I'm not absolutely positive that I didn't omit check for some serializable/non-serializable data types, which actually I think depends on the definition of "serializable" - any comments and suggestions will be welcome.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With