简体   繁体   中英

Generating json data from user input (textarea)

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.

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'));

});

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