Robert Christopher
Robert Christopher

Reputation: 459

Javascript writing to a text file on multiple lines

I am coding something that pulls a json file off a url and parses the json.
The script can filter out the data that I need and it works just fine.

Now, my goal is to have the data be written to a text file. I have achieved this, but the data is cluttered onto one line. I have posted my code below.

document.getElementById("find").addEventListener("click", sendHTTP);

function sendHTTP() 
{
    var httpreq;

    if (window.XMLHttpRequest) 
    { // code for IE7+, Firefox, Chrome, Opera, Safari
        httpreq = new XMLHttpRequest();
    } 
    else 
    { // code for IE6, IE5
        httpreq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    httpreq.onreadystatechange = function() {
        if (httpreq.readyState == 4) 
        {
            var store = httpreq.responseText;
            var me = JSON.parse(store);
            var parsed = [];
            try  
            {
                for (var i = 0; i < store.length; i++) 
                {
                    parsed.push(me.products[i].title);    // title

                    for (var j = 0; j < me.products[i].offers.length; j++) 
                    {
                        parsed.push(me.products[i].offers[j].offer_id);  // offer_id
                    }
                }
            } 
            catch (err) 
            { } 
            finally 
            {
                downloadURI("data:text/html," + parsed.join(""), "inventory.txt");
            }
        }
    };

    httpreq.open("GET", "http://shop.cncpts.com/collections/nike-sb.oembed");
    httpreq.send();
}

function downloadURI(uri, name) 
{
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

The function downloadURI performs the download.
The text file will successfully download, but the data from the json is cluttered to one line.

Is there any possible way that I could make everything go on a separate line? For example:

title
offer_id
title
offer_id.....

Upvotes: 0

Views: 1413

Answers (2)

Rohith K
Rohith K

Reputation: 1482

This should work.

downloadURI("data:text/html," + parsed.join("\r\n"), "inventory.txt");

Upvotes: 1

adeneo
adeneo

Reputation: 318172

Join with newlines

downloadURI("data:text/html," + encodeURIComponent(parsed.join("\r\n"), "inventory.txt"));

Upvotes: 4

Related Questions