git.schokokeks.org
Repositories
Help
Report an Issue
fs-words.git
Code
Commits
Branches
Tags
Suche
Strukturansicht:
faf7e12
Branches
Tags
develop-client_server
master
typescript
fs-words.git
server
source
helpers
json.ts
[mov] server
Christian Fraß
commited
faf7e12
at 2021-03-08 23:05:42
json.ts
Blame
History
Raw
namespace helpers.json { /** */ export function encode_extended ( data : any, formatted : boolean, depth : int ) : string { const indentation : string = "\t"; const break_hard : string = (formatted ? "\n" : ""); const break_soft : string = (formatted ? "\n" : ""); const indent : (offset : int)=>string = (offset => (formatted ? indentation.repeat(depth+offset) : "")); // let output : string = ''; if (data === null) { return 'null'; } else { if (! (typeof(data) === 'object')) { return JSON.stringify(data); } else { if (data instanceof Array) { const count : int = data.length; let str : string = ""; // head { str += ("[" + break_hard); } // body { let index : int = 0; for (let element of data) { str += (indent(1) + encode_extended(element, formatted, depth+1)); if (index < (count-1)) str += ","; str += break_soft; index += 1; } } // tail { str += (indent(0) + "]"); } return str; } else { const count : int = Object.keys(data).length; let str : string = ""; // head { str += ("{" + break_hard); } // body { let index : int = 0; for (let key of Object.keys(data).sort()) { const value : any = data[key]; str += (indent(1) + "\"" + key + "\": " + encode_extended(value, formatted, depth+1) + ""); if (index < (count-1)) str += ","; str += break_soft; index += 1; } } // tail { str += (indent(0) + "}"); } return str; } } } } /** */ export function encode ( thing : any ) : string { return encode_extended(thing, false, 0); } /** */ export function decode ( str : string ) : any { return JSON.parse(str); } }