node生成的json文件格式化
时间: 2023-12-11 20:02:00 浏览: 32
如果你想要将一个 JSON 文件进行格式化,可以使用 Node.js 的内置模块 `fs` 和 `JSON`。
以下是一个简单的示例代码,假设你有一个名为 `data.json` 的 JSON 文件,需要对它进行格式化:
```js
const fs = require('fs');
// 读取 JSON 文件
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) throw err;
// 将 JSON 字符串解析为对象
const obj = JSON.parse(data);
// 将对象重新转换为格式化后的 JSON 字符串
const formattedJson = JSON.stringify(obj, null, 2);
// 将格式化后的 JSON 写入文件
fs.writeFile('formatted_data.json', formattedJson, (err) => {
if (err) throw err;
console.log('JSON 文件格式化成功!');
});
});
```
这段代码首先使用 `fs.readFile()` 方法读取 `data.json` 文件内容,然后使用 `JSON.parse()` 方法将其解析为 JavaScript 对象。接着,使用 `JSON.stringify()` 方法将对象转换为格式化后的 JSON 字符串,最后使用 `fs.writeFile()` 方法将格式化后的 JSON 字符串写入名为 `formatted_data.json` 的新文件。