Christian Fraß commited on 2021-03-04 08:16:57
Zeige 1 geänderte Dateien mit 108 Einfügungen und 0 Löschungen.
... | ... |
@@ -0,0 +1,108 @@ |
1 |
+namespace helpers.json |
|
2 |
+{ |
|
3 |
+ |
|
4 |
+ /** |
|
5 |
+ */ |
|
6 |
+ export function encode_extended |
|
7 |
+ ( |
|
8 |
+ data : any, |
|
9 |
+ formatted : boolean, |
|
10 |
+ depth : int |
|
11 |
+ ) : string |
|
12 |
+ { |
|
13 |
+ const indentation : string = "\t"; |
|
14 |
+ const break_hard : string = (formatted ? "\n" : ""); |
|
15 |
+ const break_soft : string = (formatted ? "\n" : ""); |
|
16 |
+ const indent : (offset : int)=>string = (offset => (formatted ? indentation.repeat(depth+offset) : "")); |
|
17 |
+ // let output : string = ''; |
|
18 |
+ if (data === null) |
|
19 |
+ { |
|
20 |
+ return 'null'; |
|
21 |
+ } |
|
22 |
+ else |
|
23 |
+ { |
|
24 |
+ if (! (typeof(data) === 'object')) |
|
25 |
+ { |
|
26 |
+ return JSON.stringify(data); |
|
27 |
+ } |
|
28 |
+ else |
|
29 |
+ { |
|
30 |
+ if (data instanceof Array) |
|
31 |
+ { |
|
32 |
+ const count : int = data.length; |
|
33 |
+ let str : string = ""; |
|
34 |
+ // head |
|
35 |
+ { |
|
36 |
+ str += ("[" + break_hard); |
|
37 |
+ } |
|
38 |
+ // body |
|
39 |
+ { |
|
40 |
+ let index : int = 0; |
|
41 |
+ for (let element of data) |
|
42 |
+ { |
|
43 |
+ str += (indent(1) + encode_extended(element, formatted, depth+1)); |
|
44 |
+ if (index < (count-1)) str += ","; |
|
45 |
+ str += break_soft; |
|
46 |
+ index += 1; |
|
47 |
+ } |
|
48 |
+ } |
|
49 |
+ // tail |
|
50 |
+ { |
|
51 |
+ str += (indent(0) + "]"); |
|
52 |
+ } |
|
53 |
+ return str; |
|
54 |
+ } |
|
55 |
+ else |
|
56 |
+ { |
|
57 |
+ const count : int = Object.keys(data).length; |
|
58 |
+ let str : string = ""; |
|
59 |
+ // head |
|
60 |
+ { |
|
61 |
+ str += ("{" + break_hard); |
|
62 |
+ } |
|
63 |
+ // body |
|
64 |
+ { |
|
65 |
+ let index : int = 0; |
|
66 |
+ for (let key of Object.keys(data).sort()) |
|
67 |
+ { |
|
68 |
+ const value : any = data[key]; |
|
69 |
+ str += (indent(1) + "\"" + key + "\": " + encode_extended(value, formatted, depth+1) + ""); |
|
70 |
+ if (index < (count-1)) str += ","; |
|
71 |
+ str += break_soft; |
|
72 |
+ index += 1; |
|
73 |
+ } |
|
74 |
+ } |
|
75 |
+ // tail |
|
76 |
+ { |
|
77 |
+ str += (indent(0) + "}"); |
|
78 |
+ } |
|
79 |
+ return str; |
|
80 |
+ } |
|
81 |
+ } |
|
82 |
+ } |
|
83 |
+ } |
|
84 |
+ |
|
85 |
+ |
|
86 |
+ /** |
|
87 |
+ */ |
|
88 |
+ export function encode |
|
89 |
+ ( |
|
90 |
+ thing : any |
|
91 |
+ ) : string |
|
92 |
+ { |
|
93 |
+ return encode_extended(thing, false, 0); |
|
94 |
+ } |
|
95 |
+ |
|
96 |
+ |
|
97 |
+ /** |
|
98 |
+ */ |
|
99 |
+ export function decode |
|
100 |
+ ( |
|
101 |
+ str : string |
|
102 |
+ ) : any |
|
103 |
+ { |
|
104 |
+ return JSON.parse(str); |
|
105 |
+ } |
|
106 |
+ |
|
107 |
+} |
|
108 |
+ |
|
0 | 109 |