1

i have a question, i have a 'CSV file' data and it looks like this

source,xPos,target,xPos,value
user1,0,user2,1,4
user2,1,user3,2,4
user1,0,user3,2,2
user4,2
userA1,1,userA2,2,4

and I need to reform it, because my fuction uses a data set variable with in this format which is in somehow a JSON format and it should look like :

{
"nodes":[
{"node":0,"name":"user1","xPos":0},
{"node":1,"name":"user2","xPos":1},
{"node":2,"name":"user3","xPos":2},
{"node":3,"name":"user4","xPos":2},
{"node":4,"name":"userA1","xPos":1}
{"node":5,"name":"userA2","xPos":2}
],
"links":[
{"source":0,"target":1,"value":4},
{"source":1,"target":2,"value":4},
{"source":0,"target":2,"value":2},
{"source":4,"target":5,"value":4}]
}

and the sources and targets are the node numbers that they are already predefined.

Is it possible to do that in javascript ?

Chis
  • 131
  • 10
  • Read up on loops, string splitting and concatenation in JavaScript; this is parsing text and output in another text format. Have you tried anything? What resources have you looked at? See http://stackoverflow.com/help/asking for how to ask good questions. – Arve Systad Apr 07 '16 at 12:21

2 Answers2

2

Yes it is possible to do that in Javascript.

Pogrindis
  • 7,755
  • 5
  • 31
  • 44
  • I was trying and searching but didnt find any hints @Pogrindis – Chis Apr 07 '16 at 12:04
  • Crazy right ? You just need some magic fairy dust, sprinkled on your laptop, or PC of course, then if you have any code (superfluous stuff right!), it will fix itself! – Pogrindis Apr 07 '16 at 12:07
  • @Pogrindis :) Chris: here are a few useful functions : [String.prototype.split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) to split lines and columns, [Array.prototype.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to build the desired object, [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) to get a JSON string – VonD Apr 07 '16 at 12:21
0

First split the csv data by lines:

var lines = csvData.split("\n");

Then for each line split the line by comma (,)

var dataLine = lines[1].split(","); //not the 0th line as it has only the headers

Then loop dataLine with for or forEach and organize the data the way you want. Declare two json arrays one for "links" and other for "nodes". Then assign your organized data to them.

And this is one of the way it is to be done.

Himel Nag Rana
  • 744
  • 1
  • 11
  • 19