1

I am trying to load a csv data file into a d3 tree graph. I can get the json data version working but d3.csv parser doesn't return the same string.

I have tried:

treeData.forEach(function (d) { 

and:

data.map(function(d) { return [ d[" "],

but these reference specific header strings

I need to wrap the d3.csv result with:

{name: "root", children: []}

but not using jsontostring

Below shows what I have been using and the results in chrome console:

treeJSON = d3.json("test.json", function(error, treeDataJSON) { console.log(treeDataJSON); });

result: {name: "root", children: Array(6)} children: Array(6) 0: {name: "A", values: "v1", more values: "v7"} 1: {name: "B", values: "v2", more values: "v8"} 2: {name: "C", values: "v3", more values: "v9"} 3: {name: "D", values: "v4", more values: "v10"} 4: {name: "E", values: "v5", more values: "v11"} 5: {name: "F", values: "v6", more values: "v12"}

treeCSV = d3.csv("test.csv", function(error, treeDataCSV) { console.log(treeDataCSV); });

result: (6) [{…}, {…}, {…}, {…}, {…}, {…}] 0: {name: "A", values: "v1", more values: "v7"} 1: {name: "B", values: "v2", more values: "v8"} 2: {name: "C", values: "v3", more values: "v9"} 3: {name: "D", values: "v4", more values: "v10"} 4: {name: "E", values: "v5", more values: "v11"} 5: {name: "F", values: "v6", more values: "v12"}

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
twyeld
  • 43
  • 6

1 Answers1

0

The solution is quite straightforward: inside the callback, just declare a literal object and use the parsed data (that you named treeDataCSV) for setting the children value:

const treeData = {
    name: "root",
    children: treeDataCSV
};

Here is a simple demo, using d3.csvParse instead of d3.csv, but the solution is exactly the same:

const csv = `name,values,more values
A,v1,v7
B,v2,v8
C,v3,v9
D,v4,v10
E,v5,v11
F,v6,v12`;

const treeDataCSV = d3.csvParse(csv);

const treeData = {
  name: "root",
  children: treeDataCSV
};

console.log(treeData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

It's also worth mentioning that, given your d3.csv signature, you're using D3 V4 or below. That being the case, you cannot do treeCSV = d3.csv(etc..., as you are doing. For an explanation please have a look here: d3.json doesn't return my data array in D3 v4

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171