Created
September 14, 2022 21:33
-
-
Save Jim-Holmstroem/8734f9c132ebc9ebe511feba5d4f7b14 to your computer and use it in GitHub Desktop.
serializer and deserializer for javascript for externally tagged enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const gps = { | |
type: "gps", | |
long: 234, | |
lat: 344 | |
}; | |
const kmm = { | |
type: "kmm", | |
km: 34, | |
m: { | |
type: "inner", | |
i: 3 | |
}, | |
section: [1, 2, 3] | |
}; | |
function serializer(key, value) { | |
if (typeof value === "object" && "type" in value) { | |
const { type, ...internal } = value; | |
return { [type]: internal }; | |
} | |
return value; | |
} | |
console.log("stringify"); | |
console.log(JSON.stringify([gps, kmm], serializer)); | |
const str = | |
'[{"gps":{"long":234,"lat":344}},{"kmm":{"km":34,"m":{"inner":{"i":3}}}}]'; | |
function deserializer(key, value) { | |
// NOTE need to register all the variants here | |
if (["gps", "kmm", "inner"].includes(key)) { | |
return { type: key, ...value }; | |
} | |
return value; | |
} | |
console.log("parse"); | |
console.log(JSON.parse(str, deserializer)); | |
console.log("identity"); | |
console.log(JSON.parse(JSON.stringify([gps, kmm], serializer), deserializer)); | |
console.log([gps, kmm]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment