Reputation: 2382
I'm building an application, which needs a json datafile in order to further draw stuff. I'm trying to get user input into this form:
{
"nodes": [
{
"id": "n0",
"label": "A node",
"x": 0,
"y": 0,
"size": 3
},
{
"id": "n1",
"label": "Another node",
"x": 3,
"y": 1,
"size": 2
},
{
"id": "n2",
"label": "And a last one",
"x": 1,
"y": 3,
"size": 1
}
],
"edges": [
{
"id": "e0",
"source": "n0",
"target": "n1"
},
{
"id": "e1",
"source": "n1",
"target": "n2"
},
{
"id": "e2",
"source": "n2",
"target": "n0"
}
]
}
User would input the nodes in one textarea and edges in the second text area, and from this data a graph would be plotted.
What i'm trying to do is write a function, which would convert those two comma separated arrays into json format, which can be further processed. Does this make sense? Are there any alternatives, I might have missed?
Thanks for help.
Upvotes: 0
Views: 124
Reputation: 3098
Think I've pretty much got exactly what you wanted - I was super bored so I basically wrote the whole thing for you. Here's my fiddle.
Here's the code:
$("#nodes").text("n0,A node,0,0,3");
$("#edges").text("e0,n0,n1");
var graph = {
"nodes": [],
"edges": []
}
$("#graph").submit(function(event){
event.preventDefault();
var nodeArr = $(this).serializeArray()[0].value.split(",");
var nodeObj = {
id: nodeArr[0],
label: nodeArr[1],
x: nodeArr[2],
y: nodeArr[3],
size: nodeArr[4]
}
graph.nodes.push(nodeObj);
var edgeArr = $(this).serializeArray()[1].value.split(",");
var edgeObj = {
id: edgeArr[0],
source: edgeArr[1],
target: edgeArr[2]
}
graph.edges.push(edgeObj);
console.log(JSON.stringify(graph, null, '\t'));
});
Upvotes: 1