144. serialize and deserialize data types not supported in JSON

Is this helpful ?

from all members: - accepted / - tried

Obviously, JSON.parse() and JSON.stringify() are unable to handle data types that are not supported in JSON.

JSON.stringify({a:1n}) // Error

Also undefined is ignored in object properties or changed to null.

JSON.stringify([undefined]) // "[null]"
JSON.stringify({a: undefined }) // "{}"

NaN and Infinity are also treated as null

JSON.stringify([NaN, Infinity]) // "[null,null]"
JSON.stringify({a: NaN, b:Infinity}) // "{"a":null,"b":null}"

for more info, please refer to MDN.

But sometimes we might want to be able to serialize these data types.

Now please implement functions to serialize and deserialize following data types:

  1. primitives (symbol is exluded)
  2. object literals
  3. array

Object literals and arrays are consisting of primitives and might be nested

Code below is expected to work:

parse(stringify([1n, null, undefined, NaN])) // [1n, null, undefined, NaN]
parse(stringify({a: undefined, b: NaN}) // {a: undefined, b: NaN}

You can use JSON.stringify() and JSON.parse() in your code or write your own.

Let's try to solve this problem within 20 mintues.