js ts json格式化源码
时间: 2023-07-07 14:45:18 浏览: 50
以下是使用 TypeScript 编写的 JavaScript 源码,用于将 JSON 数据格式化为可读性更好的形式:
```typescript
function formatJson(json: string): string {
let i = 0;
let result = '';
let indentLevel = 0;
const newLine = '\n';
const indent = ' ';
while (i < json.length) {
const currentChar = json[i];
if (currentChar === '{' || currentChar === '[') {
result += currentChar + newLine + indent.repeat(++indentLevel);
} else if (currentChar === '}' || currentChar === ']') {
result += newLine + indent.repeat(--indentLevel) + currentChar;
} else if (currentChar === ',') {
result += currentChar + newLine + indent.repeat(indentLevel);
} else {
result += currentChar;
}
i++;
}
return result;
}
```
此函数将 JSON 字符串作为输入,并返回格式化后的字符串。它使用缩进来表示嵌套的层级,每个缩进级别使用两个空格表示。在对象和数组的开始和结束处,它会添加一个新行并增加或减少缩进级别。在每个逗号后面,它也添加一个新行和适当的缩进。