Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliable way to check if objects is serializable in JavaScript

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?

like image 432
treznik Avatar asked Jun 01 '15 17:06

treznik


1 Answers

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:

  • plain objects ("an object created by the Object constructor or one with a [[Prototype]] of null." - from lodash documentation)
  • arrays
  • strings, numbers, booleans
  • undefined

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.)

like image 122
bardzusny Avatar answered Sep 19 '22 00:09

bardzusny