Converting Object into JSON and downloading as a .json file in React - javascript

I have a javascript object that contains some information.
I want to convert this into JSON and download it as a .json file.
Seems like I can just to JSON.stringify(obj) to convert it into JSON
but how do I actually download it as a .json file?

I'm not sure this is a React-specific issue if you're just looking to download data via JavaScript, but here's a snippet I use that creates a link to download the data content, virtually clicking the element, and finally removing it from the DOM. It should support both modern browsers and older IEs:
private exportToJson(objectData: SomeObject) {
let filename = "export.json";
let contentType = "application/json;charset=utf-8;";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(JSON.stringify(objectData)))], { type: contentType });
navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement('a');
a.download = filename;
a.href = 'data:' + contentType + ',' + encodeURIComponent(JSON.stringify(objectData));
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
It's also worth noting that there are a number of ways to approach this as cited in this SO question.

For those arriving here and searching for an easier solution:
<a
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(YOURJSON)
)}`}
download="filename.json"
>
{`Download Json`}
</a>

You won't be able to create a file directly on your computer's file system as this would be a huge security risk. You cannot do this from a web page using JavaScript.
You could write a server side service to post your state to and it creates a file - you may then download the file or be content with where your server side stores it.
Another way via inMemory Create a file in memory for user to download, not through server

Related

How to save JSON into a local file on my computer? Without nodeJS?

I'm using the IP Geolocation API from Abstract
$.getJSON("https://ipgeolocation.abstractapi.com/v1/?api_key=YOUR_UNIQUE_API_KEY", function(data) {
console.log(data.ip_address);
console.log(data.country);
})
EDIT: Basically I want to create a textfile that will save all the visitor IP addresses only onto my computer since I have the source files.
How can I save data.ip_address and data.country of each user onto only my local computer and not have the user click and download anything? Save the JSON into a texfile? That JSON request is on the one and only HTML file for my Github page. I just need the simplest solution for this quick, static project. I've tried using require(fs) but I keep getting an error and read that I can't really use nodeJS for what I'm doing.
Javascript doesn't have access to the local filesystem. You need a webserver and a server side language to be able to save something to the server's filesystem.
The only solution I can think of would be to force the browser to create a file and present it as a download. Something like:
var text = data.ip_address;
text += '\n';
text += data.country;
var filename = 'myData.txt';
var blob = new Blob([text], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
This is a nasty hack but you can run this (either on your site or in your console):
const win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = JSON.stringify(data);
// So in your case
$.getJSON("https://ipgeolocation.abstractapi.com/v1/?api_key=YOUR_UNIQUE_API_KEY", function(data) {
const win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = JSON.stringify(data);
})
and then save that opened window to your local machine as a json file.
GitHub Pages does not support server-side languages such as PHP, Ruby, or Python.
-- from docs, so it's not possible to write files. GitHub pages serve static content, without any backend.
And even if it would be, collecting your users' location and IP into a GitHub repo might not be the best idea ever from privacy point of view.

Save a JSON file to server with javascript application

I'm developing a simple Javascript application where the user has some images (stored in my machine) and he is able to annotate them and then save the annotations as a JSON file.
The application is very light and simple and it is not an app server.
However, I need to save those JSON files to the machine that will be behaving as the server.
Since I cannot use Javascript for IO, is there any easy and simple way to save those files without having to implement an app server?
I used Blob to download the files.
function project_save_confirmed(input) {
if ( input.project_name.value !== _onco_settings.project.name ) {
project_set_name(input.project_name.value);
}
// onco project
var _onco_project = { '_onco_settings': _onco_settings,
'_onco_img_metadata': _onco_img_metadata,
'_onco_attributes': _onco_attributes };
var filename = input.project_name.value + '.json';
var data_blob = new Blob( [JSON.stringify(_onco_project)],
{type: 'text/json;charset=utf-8'});
save_data_to_local_file(data_blob, filename);
user_input_default_cancel_handler();
}
function save_data_to_local_file(data, filename) {
var a = document.createElement('a');
a.href = URL.createObjectURL(data);
a.download = filename;
a.click();
}
Any suggestion?
Kind regards!
Copy paste from: Download JSON object as a file from browser
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
This I believe accomplishes what you want, just makes sure that the proper headers are set, push it to an <a> tag, then click() it
You can do this in php:
<?php
//notice this will put WHATEVER is in json into file
$filename="config.json";
if (isset($_POST["json"])) {
file_put_contents($filename,$_POST["json"]);
}
?>
then for the JS side:
var fd=new FormData();
fd.append("json", JSON.stringify(_onco_project));
fetch("https://url.com",{method:"POST",body:fd})
Explanation: JS makes a new formdata, and sets "json" to the stringified json, and sends it off to the server. The php server takes this, and puts it directly into $filename. Make sure data is safe before putting it to file, as it will take whatever it is given and put it into your file!

Parse text/csv from server and download it

How to download file with data which comes from server in text/csv format?
I'm using fetch. I have function like this
download(content, filename, contentType)
{
const a = document.createElement('a');
a.href = 'data:text/csv;charset=utf-8,' + encodeURI(content);
a.target = '_blank';
a.download = filename;
a.click();
}
Response comes like object.
Hope your help!
bruteforce method: replace the filename extension with .csv and then send it to your client. You can achieve that with php.
replace filename extension with php
good solution : if you want to convert a file to csv, you will need a rather powerful api. Maybe your best bet is to read the file yourself if you know what youre expecting, and generate the CSV.

Is it possible to create an xml from json in the browser, then download that xml?

I'm about to create a client side app, which at the end should create and xml file and offer to the user to download it to the computer.
Is it possible to create and download xml from the browser?
Yes, it's possible.
function downloadXMLFromJSON(jsonString) {
let fileName = 'sample.xml';
let xmlStr = new X2JS().json2xml_str(JSON.parse(jsonString));
let a = document.createElement('a');
a.download = fileName;
a.href = URL.createObjectURL(new File([xmlStr], fileName, {type: 'text/xml'}));
a.click();
}
downloadXMLFromJSON(`{"x": "a", "y": "b"}`);
<script src="https://rawgit.com/abdmob/x2js/master/xml2json.min.js"></script>
You're going to need an external library for converting JSON to XML (x2js in this case). Then you can use an in memory a tag with download attribute to download xml file.

Download large file >1GB using http protocol, java and javascript

I have a web application for downloading files. Everything works fine except when I want to download a file more than 1GB .
This is my java code:
InputStream in = new FileInputStream(new File(folderFile.getAbsolutePath()));
org.apache.commons.io.IOUtils.copy(in, response.getOutputStream());
response.flushBuffer();
in.close();
HTTP request :
$http({
method:'get',
url:this.apiDownloadFileUrl,
responseType:'arraybuffer',
cache: false
});
and here is client side: I got data successfully on client, but when I make it Blob , if the data size was more than 500MB , nothing happened and it wasn't downloaded. Also, I can download 300MB ...
How can I check if it is a memory problem, or a server problem? ... When I download from gmail , I can download more than 1GB .
.success(function(databack) {
var file = new Blob([ databack ], {
type : 'application/csv'
});
var fileURL = window.URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = data;
document.body.appendChild(a);
a.click();
Have you tried using the copyLarge() methods from IOUtils? For the copy() methods the JavaDoc says:
"For large streams use the copyLarge(InputStream, OutputStream) method."
You should check the response message first, and decide which side fire the problem.
As my experience, you should check whether the file was cached by the browser rather than any problems~

Categories