Created
January 9, 2025 04:49
-
-
Save EdamAme-x/42d48f218e53b55bdf12d8c75032e5a1 to your computer and use it in GitHub Desktop.
compress-json
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
// @copyright EdamAme-x | |
type JSONPrimitive = string | boolean | number | null | undefined | |
type JSONArray = JSONValue[] | |
type JSONObject = { [key: string]: JSONValue } | |
type JSONValue = JSONObject | JSONArray | JSONPrimitive | |
const reservedSymbol = [ | |
"/", | |
"=", | |
"!", | |
"#", | |
"%", | |
"~", | |
"+", | |
">", | |
"<", | |
"(", | |
")", | |
"-", | |
"?" | |
] | |
const compressJson = (json: JSONValue) => { | |
const compressString = (string: string) => { | |
return `/${reservedSymbol.reduce((prev, cur) => { | |
return prev.replaceAll(cur, `\\${cur}`) | |
}, string)}` | |
} | |
const commpressBoolean = (boolean: boolean) => { | |
return boolean ? "=" : "!" | |
} | |
const compressNumber = (number: number) => { | |
return `#${number.toString()}` | |
} | |
const compressNull = () => { | |
return "%" | |
} | |
const compressArray = (array: JSONArray) => { | |
let result = ">" | |
for (const value of array) { | |
result += `${compressSwitcher(value)}` | |
} | |
return result | |
} | |
const compressObject = (object: JSONObject) => { | |
let result = "(" | |
for (const key in object) { | |
result += `?${reservedSymbol.reduce((prev, cur) => { | |
return prev.replaceAll(cur, `\\${cur}`) | |
}, key)}-${compressSwitcher(object[key])}` | |
} | |
return result | |
} | |
const compressSwitcher = (value: JSONValue) => { | |
switch (typeof value) { | |
case "string": { | |
return compressString(value) | |
} | |
case "boolean": { | |
return commpressBoolean(value) | |
} | |
case "number": { | |
return compressNumber(value) | |
} | |
case "object": { | |
if (value === null) { | |
return compressNull() | |
}else if (Array.isArray(value)) { | |
return compressArray(value) | |
}else { | |
return compressObject(value) | |
} | |
} | |
default: | |
return "" | |
} | |
} | |
return compressSwitcher(json) | |
} | |
const json = {a:12345,b:["a",0,null,true,{b:["b",2,[],false,{a:false,b:[{a:null},null,null]}]}]} | |
const compressed = compressJson(json) | |
const stringified = JSON.stringify(json) | |
console.log(compressed) | |
console.log(compressed.length) | |
console.log(stringified) | |
console.log(stringified.length) |
decompressJson
is selling
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
max: 75% minimum