4

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

2
  • Please, define "see". If you simply want to see the object, just do console.log(json). Commented Sep 25, 2017 at 10:38
  • Thanks Gerardo : my goal is to save the object in a .JSON file. Initially I also tried to have a look at it but I managed to do in the meantime using console.log(JSON.stringify(json)) Commented Sep 26, 2017 at 15:13

1 Answer 1

2

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");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.