Convert JavaScript array data to json file

479 views Asked by At

So I have this array with different links

const urls = ['myurl.com', 'localhost.com'... etc]

In the for loop I want to create an object like so, it should basically create a new object for every URL, and then pass the looped URL to the userUrl section

for(let url of urls) {
    [
       {
         user: 1,
         isVerified: true
         userUrl: url
       }
    ]
}

After the loop finishes, this data should be readable in a JSON file it should look something like this

[
  {
    user: 1,
    isVerified: true,
    userUrl: myUrl.com
  },
  {
    user: 2,
    isVerified: true,
    userUrl: localhost.com
  }
  ...etc
]
1

There are 1 answers

0
Diego D On BEST ANSWER

I tried this code on Chrome and it works correctly plus it correctly format the json data now, instructing JSON.stringify to use 4 spaces indentation.

It won't work in the snippet, but it will if you save it in your own file. I did it inside the chrome developer tools in the Sources tab as a snippet and as soon as executed the download queue was fed with the json file.

I left the live snippet here because there's the chance to see the jsonData on console anyway.

The way to programmatically send a string to a download file was inspired by this question:

How do I save JSON to local text file

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();
}

const urls = ['myurl.com', 'localhost.com'];
const data = factory(urls);
const jsonData = JSON.stringify(data,  null, 4);
console.log(jsonData);
download(jsonData, 'json.txt', 'text/plain');

function factory(urls){
  const output = [];
  for(let url of urls) {
    output.push({
      user: 1,
      isVerified: true,
      userUrl: url
    });
  }
  return output;
}