How to save JSON data built in a d3.js script

Viewed 2527

I Hi all, I'm new to javascript/D3.js programming. I need to adjust a code and I feel a bit lost.

The main question is : how to save a JSON dataset in javascript

The current code is loading a big csv file, parsing and formatting it. I want to move the file-management part in another program, but to directly get the well formatted file, I would like to save it directly by running this code and saving the output (which is: json = buildHierarchy(csv);).

Thank you for your help !

d3.text("myfile.csv", function(text) {
  var csv = d3.csv.parseRows(text);
  var json = buildHierarchy(csv);  //-- THIS IS WHAT I NEED TO SAVE (OR SEE)
});

// function to adjust data

function buildHierarchy(csv) {
  var root = {"name": "root", "children": []};
  for (var i = 0; i < csv.length; i++) {
    var sequence = csv[i][0];
    var size = +csv[i][1];
    if (isNaN(size)) { // e.g. if this is a header row
      continue;
    }
    var parts = sequence.split("-");
    var currentNode = root;
    for (var j = 0; j < parts.length; j++) {
      var children = currentNode["children"];
      var nodeName = parts[j];
      var childNode;
      if (j + 1 < parts.length) {
   // Not yet at the end of the sequence; move down the tree.
  var foundChild = false;
  for (var k = 0; k < children.length; k++) {
    if (children[k]["name"] == nodeName) {
      childNode = children[k];
      foundChild = true;
      break;
    }
  }
  // If we don't already have a child node for this branch, create it.
  if (!foundChild) {
    childNode = {"name": nodeName, "children": []};
    children.push(childNode);
  }
  currentNode = childNode;
      } else {
  // Reached the end of the sequence; create a leaf node.
  childNode = {"name": nodeName, "size": size};
  children.push(childNode);
      }
    }
  }
  return root;
};

1 Answers

I finally managed to save my file using saveAs function from https://github.com/eligrey/FileSaver.js/

var blob = new Blob([JSON.stringify(json)], {type: "text/plain;charset=utf-8"});  
saveAs(blob, "sequence_dl.JSON");

Related