Skip to content

Instantly share code, notes, and snippets.

@Jim-Holmstroem
Created September 14, 2022 21:33
Show Gist options
  • Save Jim-Holmstroem/8734f9c132ebc9ebe511feba5d4f7b14 to your computer and use it in GitHub Desktop.
Save Jim-Holmstroem/8734f9c132ebc9ebe511feba5d4f7b14 to your computer and use it in GitHub Desktop.
serializer and deserializer for javascript for externally tagged enum
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