MCPcopy
hub / github.com/loggerhead/json4u / textFormat

Function textFormat

src/lib/format/text.ts:10–62  ·  view source on GitHub ↗
(json: string, options?: ParseOptions)

Source from the content-addressed store, hash-verified

8 * @returns The formatted JSON string.
9 */
10export function textFormat(json: string, options?: ParseOptions): string {
11 const genTabs = getGenTabsFn(options?.tabWidth || 2);
12 let i = 0;
13 let il = 0;
14 let newJson = "";
15 let indentLevel = 0;
16 let inString = false;
17 let c = null;
18
19 for (i = 0, il = json.length; i < il; i += 1) {
20 c = json.charAt(i);
21
22 if (c === '"') {
23 // if not \"
24 if (i > 0 && json.charAt(i - 1) !== "\\") {
25 inString = !inString;
26 }
27 newJson += c;
28 continue;
29 } else if (inString) {
30 newJson += c;
31 continue;
32 }
33
34 switch (c) {
35 case "{":
36 case "[":
37 newJson += c + "\n" + genTabs(indentLevel + 1);
38 indentLevel += 1;
39 break;
40 case "}":
41 case "]":
42 indentLevel -= 1;
43 newJson += "\n" + genTabs(indentLevel) + c;
44 break;
45 case ",":
46 newJson += ",\n" + genTabs(indentLevel);
47 break;
48 case ":":
49 newJson += ": ";
50 break;
51 case " ":
52 case "\n":
53 case "\t":
54 break;
55 default:
56 newJson += c;
57 break;
58 }
59 }
60
61 return newJson.trim();
62}

Callers 3

prettyFormatFunction · 0.90
prettyFormatWithFallbackFunction · 0.90
format.bench.tsFile · 0.90

Calls 1

getGenTabsFnFunction · 0.90

Tested by

no test coverage detected