Save D3.js data models into files

I needed to be able to save the workspace of a project of mine into file so I can load it later. To do so, I needed to save D3 data models into a text file. Here, I’ll explain how one can save a D3 data model into a file. But, before that, I’ll have to explain a number of concepts.

 

JSON

JSON or Javascript Object Notion is a open standard format that uses plain text to transmit JS object through network. Here we are going to use JSON to write D3 models into file. A simple JSON example is shown below. Consider its similarity to JS objects’ format.

 

The JSON above is a student object and has properties such as name, student id, a list of phone numbers and a possible list of courses which is empty for now. for more information on JSON read here.

 

Javascript and JSON

In order to parse a JSON string into a JS object or vise versa you can use the JSON object in JS. Below, you can find how you can parse or create  JSON string from/to JS object.

Saving a file in JS

It is not super hard to start from scratch and save a file in javascript. Basically it is done by creating a blob object first and writing that, though in some browsers the user interface will look like you are downloading the file or it will automatically download. However, I would suggest to use the FileSaver.js developed originally by Eli Grey and support a decent number of browsers.

 

Saving D3 Data Models into File

To save a D3 data model into a file you will need to write everything into a file using JSON format. You can simply do that by creating a simple JS object which contains the DATA object with which you fed D3 in the first place. JS functions behave as a pass by reference function when it comes to JS objects. However, this may only be enough for simple examples that you are using a fixed look and feel for your graph and data is the only thing that changes between workspaces.

Inorder to save a D3 graph with different presentation functionalities such as graph’s links’ style, colors and etc. you will also need to save these functions and set them appropriately. Some of those functions are lickArc(), transform(), tick() for properties such as node width, color fill and etc. Attributes which you set when you initialize the d3 object at the beginning. But, these attributes may now have changed. How can we get these information then?

Basically, the easiest way to find these now is to loop through all the child nodes of the SVG tag and save the properties one by one.

Leave a reply:

Your email address will not be published.

Site Footer