DEV Community

Discussion on: What is a best / simplest way to serialize / deserialize JavaScript objects?

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Actually, I have now succeeded in deserializing objects (instead of Arrays). The solution is here.

GitHub logo patarapolw / any-serialize

Serialize any JavaScript objects, as long as you provides how-to. I have already provided Date, RegExp and Function.

Also, to create a MongoDB-compatible serialize, you can try.

const cond = {
  a: new Date(),
  b: /regexp/gi
}

const r = JSON.stringify(cond, function (k, v) {
  const v0 = this[k]
  if (v0) {
    if (v0 instanceof Date) {
      return { $date: v0.toISOString() }
    } else if (v0 instanceof RegExp) {
      return { $regex: v0.source, $options: v0.flags }
    }
  }
  return v
})

console.log(r)

console.log(JSON.parse(r, (_, v) => {
  if (v && typeof v === 'object') {
    if (v.$date) {
      return new Date(v.$date)
    } else if (v.$regex) {
      return new RegExp(v.$regex, v.$options)
    }
  }
  return v
}))
Enter fullscreen mode Exit fullscreen mode

I also created a Gist for the time being -- gist.github.com/patarapolw/c9fc59e...