serialize and deserialize data types not supported in JSON
2022年5月1日小于 1 分钟
serialize and deserialize data types not supported in JSON
Question
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:
- primitives (symbol is exluded)
- object literals
- 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.
Code
/**
* type SerializablePrimitives = undefined | null | number | string | bigint | boolean
* type Serializable = {
[index: string]: Serializable
} | Serializable[] | SerializablePrimitives
*/
/**
* @params {Serializable} data
* @returns {string}
*/
const stringify = (data) => {
// your code here
}
/**
* @params {string} data
* @returns {Serializable}
*/
const parse = (data) => {
// your code here
}