JSON to client-side CSV file download using vanilla JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to this tutorial so what I'm going to be showing you in this video is how you can download some data from a server in Json format and turn that into a CSV download on the client side so for this example I'm going to be fetching data from a live test API called requez.in so if you visit their website there's the documentation there what I'm going to be getting is a list of users so for that it's forward slash API forward slash users and I'm going to omit the query string with page two so I just get the first page of the users and I'm going to receive the data back in this format so this is json's string format and you can see that the data is contained on a property on the Json object called Data so I'm going to need to access the data property and then I will have available to me an array of objects where each object is a user with information contained about each user on each of the properties okay so back in JavaScript I've already entered the endpoint URL for this API request so this is going to fetch a list of users from the API and then what I need to do is handle the result so this will return a response object which is available inside the then method and what I want to do is apply the Json method to that response object what that's going to do is to read the readable stream on the response object into a native JavaScript object and that native JavaScript object is going to be available to me in the next then method so for now I'm just going to log that to the console so we can check whether this request was successful and we've got the data back so here it is is the object and you see on it is the data property so that is where the user data is stored okay so the next task is to get this data and to transform it into CSV file format so the first thing I'm going to do is create a new function down here and or so this is going to handle the result of the fetch request and now instead of logging the data to the console I'm going to pass it in to the handle function and then I have available to me here the input data within the new handle function okay so the first thing I want to do inside this handle function is to get the headers for the CSV which is really just the first row of data and I want that to be the property keys for each bit of information about a user so the way that I can get the keys of an object is by calling object.keys and I want to pass into there just the first user object so that would be input data dot data because remember it's on a property called data and I want the one the first one which would be at position zero in that array of objects okay so I'll save that in a variable called headers and let's take a look at the value of that to check it'll work Okay so we've got ID email first name last name and Avatar so these are going to be the headers in our CSV file now you'll notice that these are still in an array so what you can do to get it just in a comma separated list on one line let's say here to string so this is going to coerce that array into a comma separated list like this which is exactly what CSV format is it's a comma separated list and each of the rows are separated by a line break so we'll be adding those in a minute but this is already our first row of data okay so for the main rows of data what I want to do is iterate through the objects of user data that are located input data dot data and I'm going to use the map method on that because it's in Array format and array of objects and inside here I'm going to have each object available to me so map is going to create a new array and what I want for that new array is to get the values of each user object so for that I can use object.values passing in each item and I want each item to be coerced to string value and I'll save the result so main that's going to be the new array now so let's see what that looks like in the console so we get an array of arrays back each one with commas separating the data now the final step is to merge headers and Main so that they are joined together and each row needs to be separated by a line break so what I'm going to do is to create a new array and the first item in there is going to be headers and then I want each of the arrays contained in main to also be items in this array so to do that with shorthand I can use the spread operator so this is just like saying main zero main one main two Etc without having to write all that out so what you want to do is join them together by a line break so that's a new row of data according to CSV formatting and now you have your data in CSV format so let's take a look at that in the console so we have here the headers and then a new line with the first row of actual data and then the next row of data Etc and on each line each bit of data is separated by a comma the next step is to create a download out of this so I'm going to do this in a new function I'm going to call this start CSV download okay and that's going to have an input there and I'm going to what I'm going to do in the Handler function is I'll get rid of these console logs here because I don't need those anymore and I'll pass in that final result there into the CSV function so now to start the download what you need is a URL so with the CSV you've only got a text file the way that you can create a URL to that CSV text is to place it in a blob first of all so a blob is just a container for data and as a first argument it accepts the data you want to pass in there in Array format so that is the input and the second argument is an object in which you specify what kind of data is in there so that the server or software that is receiving it has some idea about its contents so what you enter here is a mime type so for a CSV the Mind type is application CSV so I'll save the return value of this on the blob and what you can do now is use URL dot create object URL so this creates a temporary URL to a Blog where we have a blob so you can just pass that in there now and that's going to return a temporary URL to you so let's just take a look at that URL so here we have a blob URL it looks a little bit different from a regular URL and that's because it's pointing to the blob containing the CSV data in browser memory it won't for example survive a page refresh but it will function just like a regular URL inside that browser window so for example we can start a download using a blob URL which is exactly what we are about to use it for okay so to create a download in JavaScript people want to create a new anchor element so you can do that using the create element method the next thing you want to do is to set that anchor elements download attribute so the value here is going to be whatever you want the file to be called when it's downloaded so I'll call this test CSV or CSV the next thing to set is the file URL so that's going to be the URL we created from placing that CSV text in the blob now to start that download you have to add that anchor element to the Dom so I'll do that using the pen child method passing in that new anchor element and then you can simulate a click on that element by calling the click method on that anchor element and then after the download is complete you probably want to remove it from the Dom and something else you want to do it's good practice to actually delete the URL you created so you can do that using revoke object URL so the reference for that is URL now the reason you want to do this is because all the time that this URL we created is active this blog data is being held in memory so you don't need it in memory after the URL has been used if you're sure you don't want to use it again then it's best to free up the memory that it is using now finally because this is going to be an automatic download and the user doesn't need to see the anchor element you may want to set the display value to none so that the user doesn't see that element being appended on screen okay so now if I hit refresh the download should start automatically so I downloaded test csv.csv now if I open it so it's opening in Visual Studio code I have a plugin here called edit CSV so if I hit that you'll be able to see the data in table format so you can see I've got all the data here now as a CSV now in case you don't want the CSV to start downloading automatically what you might want to do is to create a button in the markup so give that an ID of button there so button's going to say start download so what you can do in JavaScript is to add an event listener to the button and then run exactly the same process as we did before so I'll do that now just for completeness add an event listener listening out for a click then I can simply copy and paste that process from before inside the event listener so now it's only going to run when the user has clicked on that button and let's test it so if I hit start download the CSV starts downloading again this should be exactly the same file as before so here we go again we have the data but this time the download was initiated by the button not automatically okay so that's how you can turn Json data that you fetched from an API into a CSV download I hope you found this tutorial useful if you did please consider hitting the like button down below this video because it helps us with the algorithm and others to find this video and if you do want to see content like this in the future don't forget you can subscribe to the channel
Info
Channel: OpenJavaScript
Views: 5,702
Rating: undefined out of 5
Keywords:
Id: JPxzeG4N5nQ
Channel Id: undefined
Length: 13min 5sec (785 seconds)
Published: Fri Oct 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.