Best way to serialize/unserialize objects in JavaScript?

前端 未结 8 1374
忘掉有多难
忘掉有多难 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<T> (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.

    0 讨论(0)
  • 2020-11-27 14:18

    I've added yet another JavaScript serializer repo to GitHub.

    Rather than take the approach of serializing and deserializing JavaScript objects to an internal format the approach here is to serialize JavaScript objects out to native JavaScript. This has the advantage that the format is totally agnostic from the serializer, and the object can be recreated simply by calling eval().

    https://github.com/iconico/JavaScript-Serializer

    0 讨论(0)
提交回复
热议问题