ts将json格式化
时间: 2024-01-04 12:18:48 浏览: 45
以下是使用TypeScript将JSON格式化的示例代码:
```typescript
import fs from 'fs';
// 读取JSON文件
function readJson(jsonFilePath: string) {
if (fs.existsSync(jsonFilePath)) {
return JSON.parse(fs.readFileSync(jsonFilePath, 'utf-8'));
} else {
return {};
}
}
// 写入JSON文件
function writeJson(data: any, jsonFilePath: string) {
fs.writeFileSync(jsonFilePath, JSON.stringify(data, null, 4), 'utf-8');
}
// 示例数据
const myData = { name: 'test', version: '1.0' };
// 将JSON格式化并输出
const formattedJson = JSON.stringify(myData, null, 4);
console.log(formattedJson);
```
在上述代码中,我们使用了Node.js内置的fs模块来读取和写入JSON文件。readJson函数用于读取JSON文件并将其解析为JavaScript对象,writeJson函数用于将JavaScript对象转换为JSON字符串并写入JSON文件。最后,我们使用JSON.stringify方法将JavaScript对象转换为格式化后的JSON字符串,并将其输出到控制台。