Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export a Json object to a text File

I'm trying to write a Json object (JsonExport) and I'd like to write its content into a text file.

I'm using max4live to export data from Audio DAW to Json in order to export to a server, but after that I would like to see the whole Json Object in a text file:

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


 file.open("write"); // open file with write access
 file.write(str);
 file.close();

The compiler runs with no error, but i can not get the text file. I have used as well path to some of my directories and nothing.

Any idea what's happening? Thanks

like image 490
Albeis Avatar asked Nov 18 '15 12:11

Albeis


People also ask

Can I convert JSON to text?

Users can also Convert JSON File to Text by uploading the file. Download converted file with txt extension.

Is a JSON file a text file?

JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers.


2 Answers

I know this question already has accepted answer but I think my answer could help someone. So, the problem is to export Json data to a text file. Once you execute the following code, file will be downloaded by the browser.

const filename = 'data.json';
const jsonStr = JSON.stringify(JsonExport);

let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(jsonStr));
element.setAttribute('download', filename);

element.style.display = 'none';
document.body.appendChild(element);

element.click();

document.body.removeChild(element);
like image 190
NutCracker Avatar answered Sep 22 '22 16:09

NutCracker


If you have access to an already existing file, just link to it. You can specify what the downloaded file name will be like this:

<a href="path/to/file.txt" download="example.json">
    Download as JSON
</a>

If needed, you could also write out the dataURI as well

 //Get the file contents
 var txtFile = "test.txt";
 var file = new File(txtFile);
 var str = JSON.stringify(JsonExport);

 //Save the file contents as a DataURI
 var dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(str);

 //Write it as the href for the link
 var link = document.getElementById('link').href = dataUri;

Then just give the link an ID and a default href

<a href="#" id="link" download="example.json">
    Download as JSON
</a>
like image 37
FiniteLooper Avatar answered Sep 21 '22 16:09

FiniteLooper