Skip to content

Instantly share code, notes, and snippets.

@EdamAme-x
Last active January 17, 2024 00:18
Show Gist options
  • Save EdamAme-x/05c49c4929b759fced5fec0639c2f006 to your computer and use it in GitHub Desktop.
Save EdamAme-x/05c49c4929b759fced5fec0639c2f006 to your computer and use it in GitHub Desktop.
JSON minifier
const base = `
{
"a": 1,
"b": {
"c": 2,
"d": "ai",
"e": 2.3,
"f": true,
"g": null,
"h": [
1,
{
"i": 2,
"j": [2,3,4]
},
"hello"
]
}
}
`;
const strSplitRegex = /(["])(.*?)\1/gm;
function parse(code: string): string {
// e.g. ["{a:", ""hello!"", ",b:20"]
const abstractTree: {
objectLit: string,
stringLit: string
}[] = [];
let splitedString: string = code;
code.trim();
code = code.replace(strSplitRegex, (match, ...p) => {
abstractTree.push({
objectLit: (splitedString.split(match).shift() ?? "").replace(/\n/gm, "").replace(/\s/gm, ""),
stringLit: match
});
let splitedStringArray = splitedString.split(match);
splitedStringArray.shift()
splitedString = splitedStringArray.join(match).replace(match, "");
return match;
})
const serializedCode = abstractTree.map(tree => {
return tree.objectLit + tree.stringLit;
}).join("") + splitedString.replace(/\n/gm, "").replace(/\s/gm, "");
return serializedCode;
}
console.log(parse(base))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment