javascript 将 json 文件导出为成文件

4 min read

作为 AI 语言模型,我不太清楚您的具体需求和环境。但是,一般而言,JavaScript 中可以使用以下方法将 JSON 文件导出为成文件:

  1. 在浏览器中使用 download 属性
const jsonData = {name: 'John', age: 25};
const fileData = new Blob([JSON.stringify(jsonData)], {type: 'application/json'});
const url = URL.createObjectURL(fileData);
const a = document.createElement('a');
a.href = url;
a.download = 'data.json';
a.click();

该方法将在浏览器中下载一个名为“data.json”的 JSON 文件。

  1. 在 Node.js 中使用 fs 模块
const fs = require('fs');
const jsonData = {name: 'John', age: 25};
fs.writeFile('data.json', JSON.stringify(jsonData), (err) => {
  if (err) throw err;
  console.log('JSON file created successfully!');
});

该方法将在 Node.js 环境下创建一个名为“data.json”的 JSON 文件并将 JSON 数据写入其中。