Also, it is best to use minimal libraries. Prefer built-ins, rather than NPM.
I tried to use JSON.stringify
with replacer
; and JSON.parse
with reviver
, but it isn't as easy and intuitive as it seems.
This doesn't work, BTW.
function serialize (obj: any) {
return JSON.stringify(
obj,
(_, v) => v instanceof Date ? { __date__: +v } : v
)
}
function deserialize (s: string) {
return JSON.parse(
s,
(k, v) => k === '__date__' ? new Date(v) : v
}
Solution
function serialize (obj: any) {
return JSON.stringify(
obj,
function (k, v) {
if (this[k] instanceof Date) {
return ['__date__', +this[k]]
}
return v
}
)
}
function deserialize (s: string) {
return JSON.parse(
s,
(_, v) => (Array.isArray(v) && v[0] === '__date__') ? new Date(v[1]) : v
)
}
Functions should work as well, with Function.toString()
and eval(Function)
.
Questions
- Somehow, NeDB's internal uses
{ $$date: +new Date() }
with great success. I don't know how that works. - Even if I manage to get
JSON.parse
andJSON.stringify
to work withDate
, I cannot be really sure if it is more performant than third party solutions, but at least it is better than js-yaml... -
JSON.stringify
/JSON.parse
is also known to not preserve key orders. I don't know if this will be problematic in the future.
Top comments (3)
Actually, I have now succeeded in deserializing objects (instead of Arrays). The solution is here.
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.
I also created a Gist for the time being -- gist.github.com/patarapolw/c9fc59e...
The +new Date() returns the Date object parsed to number, so the same as (new Date()).getTime(). Y supose that it is easy to use, in his/her solution, the unix timestamp instead the string iso notation of the date. I don't know if you mean this.
I have a question to you too, why do you even will care about the keys being ordered?
$$date
), notArray
. I cannot even make special Object work.js-yaml
+ SparkMD5.