简体   繁体   中英

Mapping Excel Columns to Parent-Child JSON

I have a CSV input like this:

Column1,Column2,Column3,Column4,Column5
a,b,c,d,e
a,b,f,,
a,g,h,i,
j,k,l,,
j,k,m,n,
o,,,,

And I'm trying to transform that into a JSON output that complies with this format ( http://bl.ocks.org/mbostock/raw/4063550/flare.json ) so I can leverage d3.js to visualize the parent-child tree ( http://bl.ocks.org/mbostock/4063570 ).

I'm looking to visualize my data exactly like that example, but I don't have/need weights. If need be, I can add a common first-level parent. Just looking to visualize the tree(s).

Largest depth is always 5.

I was playing around with doing some array stuff in PHP (after reading in with fgetcsv()), but I was bumbling around and could use some help.

PHP or Javascript solution preferred, since that's all I can work with through my work computer setup. I really appreciate the help!

It sounds like you're looking for a tree structure where your data looks like the following:

          a            j      o
         / \          /
        b   g        k
       / \   \      / \
      c   f   h    l   m
     /         \        \
    d           i        n
   /
  e

if so, the following javascript code should do what you want:

var csv = //CSV CONTENT HERE
  , data = parseCSV(csv)
  , structure = toJSONStructure(data)
  , formattedForD3 = toNameChildFormat(structure)

console.log(formattedForD3)

function parseCSV(csv) {
    return csv.split('\n').slice(1).map(function(line) {
        return line.split(',')
    })
}

function toJSONStructure(data) {
    var structure = {}
    data.forEach(function(line) {
        var o = structure
        line.forEach(function(val) {
            if(val) o = o[val] = o[val] || {}
        })
    })
    return structure
}

function toNameChildFormat(structure) {
   return Object.keys(structure).map(function(key) {
       return {
           name:key,
           children:toNameChildFormat(structure[key])
       }
   })
}

JSFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM