Best way to serialize/unserialize objects in JavaScript?

前端 未结 8 1405
忘掉有多难
忘掉有多难 2020-11-27 13:53

I have many JavaScript objects in my application, something like:

function Person(age) {
    this.age = age;
    this.isOld = function (){
        return thi         


        
8条回答
  •  [愿得一人]
    2020-11-27 14:17

    I tried to do this with Date with native JSON...

    function stringify (obj: any) {
      return JSON.stringify(
        obj,
        function (k, v) {
          if (this[k] instanceof Date) {
            return ['$date', +this[k]]
          }
          return v
        }
      )
    }
    
    function clone (obj: T): T {
      return JSON.parse(
        stringify(obj),
        (_, v) => (Array.isArray(v) && v[0] === '$date') ? new Date(v[1]) : v
      )
    }
    

    What does this say? It says

    • There needs to be a unique identifier, better than $date, if you want it more secure.
    class Klass {
      static fromRepr (repr: string): Klass {
        return new Klass(...)
      }
    
      static guid = '__Klass__'
    
      __repr__ (): string {
        return '...'
      }
    }
    

    This is a serializable Klass, with

    function serialize (obj: any) {
      return JSON.stringify(
        obj,
        function (k, v) { return this[k] instanceof Klass ? [Klass.guid, this[k].__repr__()] : v }
      )
    }
    
    function deserialize (repr: string) {
      return JSON.parse(
        repr,
        (_, v) => (Array.isArray(v) && v[0] === Klass.guid) ? Klass.fromRepr(v[1]) : v
      )
    }
    

    I tried to do it with Mongo-style Object ({ $date }) as well, but it failed in JSON.parse. Supplying k doesn't matter anymore...

    BTW, if you don't care about libraries, you can use yaml.dump / yaml.load from js-yaml. Just make sure you do it the dangerous way.

提交回复
热议问题