Nested list html from json, csv

I have a flat csv file like

name,roll,section,hh
a,1,k,34
a,1,r,5

      

you can see that there is duplicate data of type "a" in "name". I want to convert them to nested html list like below.

|a
---------------------
   |1
   ------------------
      |k
      ---------------
            |  34
      ---------------
      |  r
      ---------------
            |  5
            ---------

      

So I thought I could convert them to nested json structure and then to html using js.

how to convert this data to nested json like below?

{
"name":"a"
"roll":"1"
"section":["k","r"],
"hh":["34","5"]
}

      

}

Is there any other way to present this csv data in a nested html list? please, help.

edit: For the json part, I converted the csv with $ .toJSON ($. Csv.toObjects (data)) using the js plugin. but couldn't find a way to do nested json as i showed.

+3


source to share


1 answer


Given input in this CSV format:

name,roll,section,hh
a,1,k,34
a,1,r,5

      

Each line of data represents a complete route from root to leaf node. This way we can split by string and copy it to JSON object. Considering that you have a function that parses the CSV text as above into an array of tokens, for example:

var lines = $.csv.toArrays(csv);

      



lines

will now become a two dimensional string array like this:

[
    ['name','roll','section','hh'],
    ['a','1','k','34'],
    ['a','1','r','5']
]

      

Ignore the first line, which is the header, loop through each line, and accumulate the JSON object:

var people = [];
lines.slice(1).forEach(function(person){
    // Check if this person has already been added to the people list?
    if (people.filter().length>0){
        // Update the existing person in the list
        for (var p in people){
            if (people[p].name === person[0]){
                people[p].section.push(person[2]);
                people[p].section.push(person[3]);
            }
        }
    }
    else{
        // Add a new one
        people.push({
            name: person[0],
            roll: person[1],
            section: [person[2],
            hh: [person[3]]
        });
    }
});

      

0


source







All Articles