How do I save JSON to local text file
Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json"
and format to .json
import { saveAs } from 'file-saver'
let data = { a: 'aaa' , b: 'bbb' }
let blob = new Blob([JSON.stringify(data)], { type: 'application/json' })
saveAs(blob, 'export.json')
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
It's my solution to save local data to txt file.
function export2txt() {
const originalData = {
members: [{
name: "cliff",
age: "34"
},
{
name: "ted",
age: "42"
},
{
name: "bob",
age: "12"
}
]
};
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {
type: "text/plain"
}));
a.setAttribute("download", "data.txt");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
<button onclick="export2txt()">Export data to local txt file</button>