Skip to content

Instantly share code, notes, and snippets.

@m5r
Forked from eliseumds/serverJson.ts
Created December 31, 2019 06:53
Show Gist options
  • Save m5r/bcc33f79366297c949693cf7624000c5 to your computer and use it in GitHub Desktop.
Save m5r/bcc33f79366297c949693cf7624000c5 to your computer and use it in GitHub Desktop.
export function serializeServerDataToJsonString(data: Object): string {
const jsonString = JSON.stringify(data);
return jsonString
.replace(/<\/script/gim, '</_escaped_script')
.replace(new RegExp('\u2028', 'g'), '\\u2028')
.replace(new RegExp('\u2029', 'g'), '\\u2029')
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\f/g, '\\f')
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/&/g, '\\&');
}
export function deserializeServerDataFromJsonObject(jsonObject: Object): Object {
try {
const target = JSON.stringify(jsonObject);
return JSON.parse(target.replace(/<\/_escaped_script/gm, '</script'));
} catch (error) {
console.error(error, { errorName: 'Failed to deserialize server data' });
return jsonObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment