Search code examples
jsonjstree

Use custom Json data in jstree form


Here is a part of my input Json data file :

{
  "id": "ns=2:s=Configured Tags",
  "text": "Configured Tags",
  "path": "Configured Tags",
  "children": [
    {
      "id": "ns=2:s=[System]",
      "text": "System",
      "path": "Configured Tags/System",
      "children": [
        {
          "id": "ns=2:s=[System]Gateway",
          "text": "Gateway",
          "path": "Configured Tags/System/Gateway",
          "children": []
        }]
    }]
 }

Here I have custom field path, but I need a few others like dataType etc.

I want to return, as an input value of my form, a concatenated string from custom fields.

Here is my form and the jstree script part :

<form id="form" action="/opc_add_data" method="post">
            <div id="tree"></div>
            <br>
            <button class="btn-flat inverse pull-right" name="submit" id="submit" onclick="return confirm('Are you sure?')" type="submit">Confirm</button>
        </form>


    $('#form').submit(function() {
        var data = $('#tree').jstree(true).get_bottom_selected(true);
        for(var count = 0; count < data.length; count++){
           $(this).append('<input type="text" name="' + data[count]["id"] + '" value="' + data[count]["path"] + '" hidden/>');
        }
        return true;
    });

Part of my form process (Python2.7):

        for key in request.form.keys():
        if key != "submit":        
            description.append(re.sub('[^a-zA-Z0-9 \n.]', '_', request.form.get(key)))

If I try to get data[count]["id"] and data[count]["text"] I succeed, because text and id are fields described in the doc. But when I try with my custom, I get "undefined" as value.

My question is: can I really do what I want, i.e. get a custom field this way data[count]["path"]?


Solution

  • Well, debug helped me to find my own answer (as if I've asked the question too quickly):

    All those key:value pairs, doc-defined as custom defined, are stored in the original attribute of the node object. Thus we can access custom by using this syntax (in my case):

    data[count]["original"]["path"]

    Or even define a new structure in the Json:

    {
          "id": "ns=2:s=[System]Gateway",
          "text": "Gateway",
          "attr": {
                   "path": "Configured Tags/System/Gateway",
                   "other": "other_value"
          },
          "children": []
    }
    

    and then use data[count]["original"]["attr"]["path"]