How to Save JSON to Local Text File

How do I save JSON to local text file

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');

How do I write JSON data to a file?

data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)

See json documentation.

Save JSON data to text file and read it

Is there possible to save JSON data into local text file?

Yes. Currently JavaScript at linked jsfiddle creates a .txt file, not a valid JSON file.

You can use try..catch..finally and JSON.parse() to check if input at <textarea> element is valid JSON. If .value of <textarea> is valid JSON create Blob URL using Blob or File constructor with MIME type property set to "application/json". and URL.createObjectURL(), else notify user that input is invalid JSON.

(function () {
let file, url, reader = new FileReader; function createJSONFile(json) { let e = void 0; try { JSON.parse(json) } catch (err) { e = err; code.textContent = e; } finally { if (e) { code.classList.add("invalid"); return "Invalid JSON"; } else { code.classList.remove("invalid"); file = new File([json], "info.json", {type:"application/json"}); url = URL.createObjectURL(file); return url; } } }; function revokeBlobURL() { window.removeEventListener("focus", revokeBlobURL); URL.revokeObjectURL(url); if (file.close) { file.close(); } } function readJSON(e) { reader.readAsText(input.files[0]); } let create = document.getElementById("create"), textbox = document.getElementById("textbox"), code = document.querySelector("code"), input = document.querySelector("input[type=file]"), pre = document.querySelector("pre");
create.addEventListener("click", function () { var link = document.createElement("a"); link.setAttribute("download", "info.json"); var json = createJSONFile(textbox.value); if (json !== "Invalid JSON") { link.href = json; document.body.appendChild(link); code.textContent = "Valid JSON"; link.click(); window.addEventListener("focus", revokeBlobURL); } else { code.textContext = json; } }, false); reader.addEventListener("load", function() { pre.textContent = JSON.stringify(reader.result, null, 2); }); input.addEventListener("change", readJSON);})();
code {  display:block;  width: 350px;  height: 28px;  border: 1px dotted green;  padding: 4px;  margin: 4px;  color: green;}
.invalid { border: 1px dotted red; color: red;}
pre { background: #eee; width: 350px; height: 350px; border: 1px solid darkorange;}
<textarea id="textbox" placeholder="Input valid JSON"></textarea><br><button id="create">Create file</button> <br><code></code><input type="file" accept=".json" /><pre></pre>

Export a Json object to a text File

Finally I got it! It worked by changing few parameters like this:

   var txtFile = "/tmp/test.txt";
var file = new File(txtFile,"write");
var str = JSON.stringify(JsonExport);

log("opening file...");
file.open();
log("writing file..");
file.writeline(str);
file.close();

Path to my directories not allowed, so i had to save it on /tmp directory.
Thanks to all!

Writing a json object to a text file in javascript

One thing you can do is setup the JSON as a download on the fly.

var data = "{name: 'Bob', occupation: 'Plumber'}";
var url = 'data:text/json;charset=utf8,' + encodeURIComponent(data);
window.open(url, '_blank');
window.focus();

Working demo: http://jsfiddle.net/sLq3F/

Apart from that, you can't write a JSON to a file on the clientside due to security reasons. (Otherwise you have access to the filesystems of your website's users.) You would have to use a server-side language for this, and store the file on the server-side.


Correction: Looks like you can write to a file, i.e., a "sandboxed section" of the user's filesystem. See Kevin Jantzer's comment below.

Another Correction: Sorry, the Filesystem API isn't in use. From the HTMl5Rocks website: "In April 2014, it was announced on public-webapps that the Filesystem API spec should be considered dead. Other browsers have showed little interest in implementing it."

Write to a local JSON file from the browser

As ArtemSky said, You can't write to the local file system. The way to accomplish what you want to do would be to use a server that can write to it's local file system or a database or whatever.

So you would want to have the data stored somewhere, either a local file on the server, in the cloud, etc. or a database of some sort. Then you would set up an API on the server that you could call remotely to get the data via an XMLHttpRequest(XHR)

Then you would create another API method you can use to send the data back and then call that with the updated/new data.

Writing to the local file system is a security concern because if anyone who can write code could overwrite your system files otherwise. Preventing the ability to write to the local file system is the only way to make the web safe.



Related Topics



Leave a reply



Submit