Skip to content Skip to sidebar Skip to footer

Loading Json As Variable Into JsTree

I am using jstree with Json. My problem is that I can provide the Json directly into jsTree data, but when I pass it as a variable it will print the entire Json string as the title

Solution 1:

In your original question data is a string (since you are using .responseText), to make it work as a variable, you should have used JSON.parse to convert the string to an array of objects.

Best regards, Ivan


Solution 2:

$.jstree.defaults.core.themes.responsive = true;
$('#tree').jstree({
    plugins: ["checkbox", "types"],
    "types": {
        "file": {
            "icon": "jstree-file"
        }
    },
    'core': {
        'data': {
            'url': function(node) {
                return 'nodes.json'
            },
            'data': function(node) {
                return {
                    'id': node.id
                };
            }
        }
    }
});

I just followed Ivan's JSTree API more closely. His API is fantastic and following it closely will save you a lot of headache. ALSO, my json had a trailer comma I beleive and was invalid, so I had to fix that as well. I tested using a json validator.


Solution 3:

I know you have already answered your own question, but I'd like to tell what's probably the cause of it anyway.

When looking at nodes.json you provided us with, I'd have to say that it isn't properly formatted as JSON. It is clearly an array, but not formatted as such. Thus you have multiple root elements, which is invalid JSON.

If you'd change nodes.json to this:

[{
  "id": "ajson1",
  "parent": "#",
  "text": "Simple root node"
}, {
  "id": "ajson2",
  "parent": "#",
  "text": "Root node 2"
}, {
  "id": "ajson3",
  "parent": "ajson2",
  "text": "Child 1"
}, {
  "id": "ajson4",
  "parent": "ajson2",
  "text": "Child 2"
}]

And in your javascript:

 request = $.getJSON("nodes.json");
 var data;
 request.complete(function() {

   data = request.responseText;
   console.log(data);
   $.jstree.defaults.core.themes.responsive = true;
   $('#tree').jstree({
     plugins: ["checkbox", "sort", "types", "wholerow", "search"],
     "types": {
       "file": {
         "icon": "jstree-file"
       }
     },
     'core': {
       'data': data
     }
   });
 });

I think your problem would've been solved already.

Since your 'answer' doesn't fix the JSON, I'd say it's the wrong answer, and I advice you to try the things I suggested above.


By the way, a handy tool to validate your JSON with in the future: http://jsonformatter.curiousconcept.com/

Please note that you may, or may not have to use $.parseJSON(data);


Post a Comment for "Loading Json As Variable Into JsTree"