Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Download jsonarray file express, node, angular

In a webapp I’m doing, there are jsonarray files that are created. For example, they look like:

[{attr1:"123",attr2:"456"},{attr1:"abc",attr2:"def"}]

I am trying to send these jsonarray files to the client and they should be downloaded exactly as they in the server, they should not be opened or parsed.

In express I have tried using, send, sendFile and download

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Disposition', 'attachment; filename=file.json');

res.sendFile(name, function (err) {
    if (err) {
         console.log('error sending:', name, err);
    } else {
         console.log('Sent:', name);
    }
});

in the front end I am using file-saver

this.Service.get(filename).subscribe(
    result => {
        console.log(result)
        let blob = new Blob(result, {type: "application/json"});
        saveAs(blob, collectionname+".json");
    }
);

and when i open the file in the client it looks like this:

[object Object][object Object]

But then I console.log() the result, I see the json objects.

What can I do?


Versions of my setup:
Angular CLI: 12.0.5
Node: 14.16.1
Package Manager: npm 7.11.1
Angular: 12.0.5

>Solution :

Blob cannot take json objects as argument (not even array of json objects).
You could pass an array of strings, e.g.

new Blob(result.map(x=>JSON.stringify(x)), {type: "application/text"});

Raed the Blob documentation for details.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading