git.schokokeks.org
Repositories
Help
Report an Issue
fs-words.git
Code
Commits
Branches
Tags
Suche
Strukturansicht:
ad82870
Branches
Tags
develop-client_server
master
typescript
fs-words.git
source
helpers
json.ts
[add] helper:json
Christian Fraß
commited
ad82870
at 2021-03-04 08:16:57
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); } }